- Home /
Component extension methods not showing
How come extension methods for Component are not shown in Mono's Intellisense when used in a MonoBehaviour script?
In a MonoBehaviour script, you can call directly GetComponent (), since MonoBehaviour inherits from Component, but you can't do that with an extension method. You have to specify the "this" reference.
Example :
public static class ComponentExtensions {
public static void DebugName (this Component c) {
Debug.Log(c.name);
}
}
public class MyClass : MonoBehaviour {
void Start () {
DebugName (); // Does not compile!!
this.DebugName () // Works as intended
}
}
Is this the intended behaviour ?
After a few test, I realized it's not just doing that with a $$anonymous$$onoBehaviour script, but with every script (normal class too).
It is probably the intended behaviour, but still, it feels weird to specify the this pointer to access extension methods
Answer by Lovrenc · May 29, 2014 at 12:40 AM
On instance methods, 'this' is implicitly passed to each method transparently, so you can access all the members it provides.
Extension methods are static. By calling Method() rather than this.Method() or Method(this), you're not telling the compiler what to pass to the method.
You might say 'why doesn't it just realise what the calling object is and pass that as a parameter?'
The answer is that extension methods are static and can be called from a static context, where there is no 'this'.
Your answer
Follow this Question
Related Questions
How do I change component properties without overriding them with parent component? 1 Answer
Get OnMouseUp event in other object's script 1 Answer
Reference Components with Iron Python 0 Answers
Copying a Component's values without a new Game Object 1 Answer
Is it possible to mark MonoBehaviour as EditorOnly 2 Answers