void AutoInjectUGUI(BaseUI _go) { Type type = _go.GetType(); //fields :Get All Pulic Fields FieldInfo[] fis = type.GetFields(); for (int i = 0; i < fis.Length; i++) { FieldInfo fi = fis[i]; // Get AutoUGUI Attribute object[] attributes = fi.GetCustomAttributes(typeof(AutoUGUI), true); if (attributes.Length > 0) { AutoUGUI att = attributes[0] as AutoUGUI; SetValueByAttribute(_go, att, fi); } } }
private void SetValueByAttribute(BaseUI _target, AutoUGUI attribute, FieldInfo _fi) { string fieldName = _fi.Name; Type type = _fi.FieldType; GameObject obj = _target.gameObject; Transform tf = null; if (!string.IsNullOrEmpty(attribute.Path)) { tf = obj.transform.Find(attribute.Path); } else { Component[] pComp = obj.transform.GetComponentsInChildren(type); for (int i = 0; i < pComp.Length; i++) { if (pComp[i].name.Equals(fieldName)) { tf = pComp[i].transform; break; } } } if (tf != null && !type.IsValueType && tf.GetComponent(_fi.FieldType) != null) { try { // _fi in _target,Set Value To _fi _fi.SetValue(_target, tf.GetComponent(type)); //Debug.Log("注册UGUI:" + fieldName); } catch (Exception e) { Debug.LogWarning("注册UGUI失败:" + e); } } }