一種代碼自動綁定控件的方法

https://blog.csdn.net/EIE08027/article/details/102987562
上篇介紹到資源與腳本的分離方法,若能做到腳本添加到預製中,並能自動綁定控件,則可以完全做到資源與腳本分離,也極大方便了程序的開發。

步驟一:定義基類BaseView

public class BaseView : MonoBehaviour
    {
        private static readonly List<string> keyHeads = new List<string>()
        {
            "btn_", "image_", "txt_", "ipt_"
        };

        private Dictionary<string, GameObject> _dicObjectList = new Dictionary<string, GameObject>();

        protected virtual void Awake()
        {
            InitComponent();
        }

        private void InitComponent()
        {
            var childArray = GetComponentsInChildren<Transform>(true);
            if (childArray != null && childArray.Length > 0)
            {
                foreach (var childTf in childArray)
                {
                    int index = childTf.name.IndexOf("_", StringComparison.Ordinal);
                    if (index == -1)
                    {
                        continue;
                    }

                    string head = childTf.name.Substring(0, index + 1);
                    if (keyHeads.Contains(head))
                    {
                        if (!_dicObjectList.ContainsKey(childTf.name))
                        {
                            _dicObjectList[childTf.name] = childTf.gameObject;
                        }
                        else
                        {
                            Debug.LogError(string.Format("key:{0} has exist,please check", childTf.name));
                        }
                    }
                }
            }
        }

        protected T GetComponentByObjName<T>(string name) where T : MonoBehaviour
        {
            if (_dicObjectList.ContainsKey(name) && _dicObjectList[name] != null)
            {
                return _dicObjectList[name].GetComponent<T>();
            }

            return default;
        }
    }
  • 其中變量keyHeads,定義了預製中識別控件的關鍵字,這裏只簡單定義了Button,Text,Image,InputField的關鍵字,後續擴展可根據規範自己在添加。
  • 在Awake方法中遍歷控件,添加到字典中。其中用到方法 GetComponentsInChildren(true);
    即使控件active爲false也可以獲取到。
  • 定義獲取控件的方法 GetComponentByObjName(string name) 傳入控件名稱和類型,通過字典即可獲取。

步驟二:腳本繼承BaseView

   [AASKey("TestBindComponentPrefab")]
    public class TestBindComponentPrefab : BaseView
    {
        private Button btn_click;
        private Text txt_content;
        private Image image_bg;
        private InputField ipt_name;
        private const string Sprite_Key = "TestImage";

        protected override void Awake()
        {
            base.Awake();
            BindComponent();
            //TODO 需要判空
            btn_click.onClick.AddListener(OnBtnClick);
            txt_content.text = "hello world!!!";
            ipt_name.text = "unity3d";
            Addressables.LoadAssetAsync<Sprite>(Sprite_Key).Completed += op => { image_bg.sprite = op.Result; };
        }

        private void OnBtnClick()
        {
            Debug.LogError("OnBtnClick Event");
        }

        private void BindComponent()
        {
            btn_click = GetComponentByObjName<Button>("btn_click");
            txt_content = GetComponentByObjName<Text>("txt_content");
            image_bg = GetComponentByObjName<Image>("image_bg");
            ipt_name = GetComponentByObjName<InputField>("ipt_name");
        }
    }

步驟三:預製製作

在這裏插入圖片描述
後續資源不管怎麼調,只要關鍵字還在,就能獲取到相應的控件。

資源獲取

https://download.csdn.net/download/EIE08027/11970159

免費獲取,可以加我qq:416390409獲取,備註csdn
PS:後期有空會更新

  • 對象池與Addressable Asset System的聯合使用
  • Android開發中,控件的綁定通常是採用Butterknife插件,通過註解的方式綁定控件,後續會採用相同的方式實現。
  • 還有很多工具想與大家分享有空會持續更新。敬請期待
發佈了15 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章