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插件,通过注解的方式绑定控件,后续会采用相同的方式实现。
- 还有很多工具想与大家分享有空会持续更新。敬请期待