扩展 MonoBehaviour 的扩展方法

Extension methods to extend MonoBehaviour

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

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应该是隐式的吧?

所以我假设我做错了什么...

这里是我使用扩展的地方:

public class SomeController : MonoBehaviour {

    private SomeComponent component;

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

我希望我说清楚了我的问题。有没有办法正确扩展 MonoBehaviour(w/o 需要显式使用 this 关键字)或者为什么它会这样?

这是(语言)设计的。

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

但是,对于您的情况,更好的解决方案是:

public class YourMonoBehaviourBase : MonoBehaviour {

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

那你就可以用了:

public class SomeController : YourMonoBehaviourBase {

    private SomeComponent component;

    void Awake() {
        // No explicit this necessary:
        component = GetComponentInChildren<SomeComponent>(true);
    }
}