- Home /
Extension method not visible in Inspector
I've created an extension method for CanvasGroup that can be called from code and works fine, but doesn't show up when trying to assign it to a button's OnClick() event. It's not visible in the list of functions in the inspector. Am I missing a tag like [SerializeField] or something above the method or class containing the extension? Thanks.
public static class CanvasGroupFadeExt
{
public static void Fade(this CanvasGroup obj, float speed)
{
UIFunction.Fade(obj, speed, true);
}
}
Answer by Hellium · Jul 09, 2019 at 06:16 AM
Extension methods are static methods which does not belong to the type. Yes, you can call GetComponent<CanvasGroup>().Fade( value )
, but behind the scene, it's the static method which is called.
When listing the methods in the inspector, Unity retrieves only the methods which:
- are not static
- declared public
- have a return type of void
- takes one or one parameter (parameter must be of type float
, int
, string
, bool
, UnityEngine.Object
)
Thanks, I figured it was some inspector-specific thing but I couldn't find it in the docs. Guess I'll just have to work around the inspector.
Right, extension methods are just syntactic sugar. So when you write this:
GetComponent<CanvasGroup>().Fade( value ),
the compiler tries to find a method that matches this signature on the CanvasGroup. If none is found it searches for an extension method. If one is found it actually does this:
CanvasGroupFadeExt.Fade(GetComponent<CanvasGroup>(), value);
The extension method is not part of the actual class. It's completely seperate and does not belong to the class it is extending. Extension classes are often located in a seperate namespace (best example are the System.Linq extensions).