首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >扩展MonoBehaviour的扩展方法

扩展MonoBehaviour的扩展方法
EN

Stack Overflow用户
提问于 2015-07-31 12:39:51
回答 1查看 4.3K关注 0票数 1

我的目标是用我的功能从MonoBehaviour引擎扩展Unity3D对象。我就是这样做的:

代码语言:javascript
复制
public static class Extensions {

    public static T GetComponentInChildren<T>(this UnityEngine.MonoBehaviour o, bool includeInactive) {
        T[] components = o.GetComponentsInChildren<T>(includeInactive);
        return components.Length > 0 ? components[0] : default(T);
    }
}

但是当我要使用它时,我只能在调用之前使用this才能访问它:this.GetComponentInChildren(true)但是this应该是隐式的,对吗?

所以我想我做错了什么..。

这里是我使用分机号的地方:

代码语言:javascript
复制
public class SomeController : MonoBehaviour {

    private SomeComponent component;

    void Awake() {
        component = this.GetComponentInChildren<SomeComponent>(true);
    }
}

我希望我把问题弄清楚了。是否有一种正确扩展MonoBehaviour的方法(w/o需要显式使用this关键字),或者为什么要这样做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-31 13:09:14

这是(语言)设计的。

如果在类中使用扩展方法,则需要显式this。换句话说,显式object expression.点运算符必须在扩展方法调用之前。如果在内部使用,这是this

然而,就您的情况而言,更好的解决办法是:

代码语言:javascript
复制
public class YourMonoBehaviourBase : MonoBehaviour {

    public T GetComponentInChildren<T>(bool includeInactive) {
        T[] components = GetComponentsInChildren<T>(includeInactive);
        return components.Length > 0 ? components[0] : default(T);
    }
}

然后你可以使用它:

代码语言:javascript
复制
public class SomeController : YourMonoBehaviourBase {

    private SomeComponent component;

    void Awake() {
        // No explicit this necessary:
        component = GetComponentInChildren<SomeComponent>(true);
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31746448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档