找回密码
 立即注册
查看: 348|回复: 0

对unity3d现有的类扩展,添加自定义的方法

[复制链接]
发表于 2022-4-10 16:25 | 显示全部楼层 |阅读模式
在调用unti3d的某个类的方法时,有可能类调用路径太长,或有些我们需要的方法,unity3d本身的类没有提供,这个时候,我们就可以对unity3d现在有类进行扩展,例如:
在查询某个组件时,一般我们这样写:
public class TopBarController : MonoBehaviour{    private LabelText scoreLableText;    private LabelText goldLableText;    // Start is called before the first frame update    void Start()    {        this.scoreLableText = this.transform.Find("ScoreLabelText").GetComponent<LabelText>();        this.scoreLableText.SetName("分数:");        this.goldLableText = this.transform.Find("GoldLabelText").GetComponent<LabelText>();        this.goldLableText.SetName("金币:");    }}
在代码中,我们想获取某个组件的代码,调用的时候,是先获取组件,调用路径会多一步,但是我们可以扩展Unity的Transform类的方法,例如:
public static class UIExtension {    public static T FindComponent<T>(this Transform parent,string path) {        return parent.Find(path).GetComponent<T>();    }}
注意,这里必须是表态类。
在使用的时候,就可以这样使用了:
public class TopBarController : MonoBehaviour{    private LabelText scoreLableText;    private LabelText goldLableText;    // Start is called before the first frame update    void Start()    {        this.scoreLableText = this.transform.FindComponent<LabelText>("ScoreLabelText");        this.scoreLableText.SetName("分数:");        this.goldLableText = this.transform.FindComponent<LabelText>("GoldLabelText");        this.goldLableText.SetName("金币:");    }}
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-22 15:31 , Processed in 0.064254 second(s), 22 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表