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

在调用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("金币:");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容