Unity 反射绑定UI

ui的名称和定义的字段名要保持一致

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UBind : MonoBehaviour {
    [SerializeField]
    public UIElement element;
    public float UI_Gps { set => element.Value_Gps = value; }
    public float UI_TagRight { set => element.Value_TagRight = value; }
    public float UI_TagLeft { set => element.Value_TagLeft = value; }

    private void Start() {
        element = new UIElement();
        InitBinding(element);
    }

    // 利用反射的机制来实现 ui绑定
    public void InitBinding(UIElement obj) {
        Type t = obj.GetType();//获得该类的Type

        FieldInfo[] allFieldInfo = t.GetFields(BindingFlags.Instance | BindingFlags.Public);//BindingFlags.NonPublic
        string[] fieldNames = allFieldInfo.Select(u => u.Name).ToArray();

        UIBehaviour[] list = transform.GetComponentsInChildren(); //UIEvnet

        for (int i = 0; i < fieldNames.Length; i++) {
            bool isFind = false;
            foreach (UIBehaviour con in list) {
                // UI结尾是 字段名
                if (con.name.Contains(fieldNames[i])) {
                    isFind = true;
                    if (con.GetType() == allFieldInfo[i].FieldType) {
                        allFieldInfo[i].SetValue(obj, con);
                    } else {
                        print($"{fieldNames[i]}对应的UI,类型不对: ${con.GetType()}");
                    }
                }
            }
            if (isFind == false) {
                print($"配置的字段 [{fieldNames[i]}] 没有绑定的 UI");
            }
        }
    }

}

[System.Serializable]
public class UIElement {
    public Text Text_Gps;
    public Text Text_TagRight;
    public Text Text_TagLeft;

    public float Value_Gps {
        set { if (Text_Gps) Text_Gps.text = value.ToString(); }
        get { return Text_Gps ? float.Parse(Text_Gps.text) : -1; }
    }
    public float Value_TagRight {
        set { if (Text_TagRight) Text_TagRight.text = value.ToString(); }
        get { return Text_TagRight ? float.Parse(Text_TagRight.text) : -1; }
    }
    public float Value_TagLeft {
        set { if (Text_TagLeft) Text_TagLeft.text = value.ToString(); }
        get { return Text_TagLeft ? float.Parse(Text_TagLeft.text) : -1; }
    }
}

你可能感兴趣的:(unity)