I seek for someone to review my code and give some suggestion, thanks.
/* Code below is use for handle attached component on children or GameObject by C# Attribute. my email : smartether@gmail.com **/
/* 一下代码用于通过c#的注解来获取组件或者gameobject **/
using UnityEngine;
using System.Collections;
[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field)]
public class PropertyAtt : System.Attribute
{
public static void Init(MonoBehaviour mb, string path = "")
{
System.Type tp = mb.GetType();
System.Reflection.FieldInfo[] fieldInfos = tp.GetFields(System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
foreach (System.Reflection.FieldInfo fieldInfo in fieldInfos)
{
System.Attribute[] atts = fieldInfo.GetCustomAttributes(typeof(PropertyAtt), false) as System.Attribute[];
if (atts != null && atts.Length > 0)
{
PropertyAtt att = atts[0] as PropertyAtt;
object value = null;
if(att.m_isComponent){
value = mb.transform.FindChild(string.Concat(path, att.m_findWithFieldName ? fieldInfo.Name.Replace("m_", "") : att.m_TargetName)).GetComponent(fieldInfo.FieldType);
}
else{
value = mb.transform.FindChild(string.Concat(path, att.m_findWithFieldName ? fieldInfo.Name.Replace("m_", "") : att.m_TargetName)).gameObject;
}
fieldInfo.SetValue(mb, value);
}
}
}
public string m_TargetName { get; set; }
public bool m_isComponent { get; set; }
/* fieldName = m_Name => targetName = Name **/
public bool m_findWithFieldName { get; set; }
public PropertyAtt(bool isComponent = true, string TargetName= "")
{
m_isComponent = isComponent;
m_findWithFieldName = TargetName == string.Empty;
if(!m_findWithFieldName)
m_TargetName = TargetName;
}
public PropertyAtt(string TargetName , bool isComponent = true)
{
m_isComponent = isComponent;
m_findWithFieldName = TargetName == string.Empty;
if (!m_findWithFieldName)
m_TargetName = TargetName;
}
}
/********Use**example************/
[PropertyAtt("BagFram")]
UITexture m_BagFram;
[PropertyAtt("BagImage")]
UITexture m_BagImage;
[PropertyAtt("BagTypeIcon")]
UISprite m_BagTypeIcon;
[PropertyAtt("BagTypeName")]
UISprite m_BagTypeName;
[PropertyAtt("BagIntroduce")]
UISprite m_BagIntroduce;
[PropertyAtt("SpecialLabelGrid")]
UIGrid m_SpecialLabelGrid;
[PropertyAtt("DrawOneBtn")]
UISprite m_DrawOneBtn;
[PropertyAtt("DrawOneBtn/NeedNum")]
UILabel m_DrawOneNeedNum;
[PropertyAtt("DrawOneBtn/MoneyIcon")]
UISprite m_DrawOneMoneyIcon;
[PropertyAtt("DrawTenBtn")]
UISprite m_DrawTenBtn;
[PropertyAtt("DrawTenBtn/NeedNum")]
UILabel m_DrawTenNeedNum;
[PropertyAtt("DrawTenBtn/MoneyIcon")]
UISprite m_DrawTenMoneyIcon;
[PropertyAtt("FreeColdDown")]
UILabel m_FreeColdDown;
[PropertyAtt("FreeNum")]
UILabel m_FreeNum;
[PropertyAtt("FreeMax")]
UILabel m_FreeMax;
void Awake()
{
PropertyAtt.Init(this, "MainWidget/");
}