2

my goal is to extend the MonoBehaviour object from Unity3D engine with my functionality. This is what I do:

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);
    }
}

But when I am going to use it, I can only access it when I use this in front of the call: this.GetComponentInChildren(true) But this should be implicit, right?

So I assume I am doing something wrong...

Here is where I use the extension:

public class SomeController : MonoBehaviour {

    private SomeComponent component;

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

I hope I made my problem clear. Is there a way to extend the MonoBehaviour correctly (w/o the need to use the this keyword explicitly) or why is it behaving that way?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Gering
  • 3,010
  • 3
  • 21
  • 23
  • 1
    Take a look at this so [question](http://stackoverflow.com/questions/3510964/why-is-the-this-keyword-required-to-call-an-extension-method-from-within-the-e). – Alessandro D'Andria Jul 31 '15 at 12:41

1 Answers1

4

This is by (language) design.

If you use an extension method inside the class an explicit this is expected. With other words, an explicit object expression and the . dot operator must preceed the extension method call. In case of inside usage this is this

However a better solution in your case would be:

public class YourMonoBehaviourBase : MonoBehaviour {

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

then you can use it:

public class SomeController : YourMonoBehaviourBase {

    private SomeComponent component;

    void Awake() {
        // No explicit this necessary:
        component = GetComponentInChildren<SomeComponent>(true);
    }
}
g.pickardou
  • 32,346
  • 36
  • 123
  • 268