Hi Guys,
Is it possible to do C# Extension methods in unity? 
What I am trying to do is extend GameObjects - as an example:
using UnityEngine;
using System.Collections;
public static class MyExtensions {
public static void MyExtendedMethod(this GameObject gameObject) {
// Do something
}
}
using UnityEngine;
using System.Collections;
public class MyScript : MonoBehaviour {
void Start () {
GameObject.MyExtendedMethod();
}
}
Everything seems fine, monodevelop picks up my extended class when I go âGameObjectâ â.â ->MyExtendedMethod() but gives a error message
error CS0117: `UnityEngine.GameObject' does not contain a definition for `MyExtendedMethod'
Thanks in advance!
EDIT: nevermind.
Not sure, maybe Unity doesnât factor those in.
At the very least, you can definitly work around them if they arenât supported.
Using a instance of a object works.
myGameObject.MyExtensionMethod();
Which is great, but I want to also be able to do
GameObject.MyExtensionMethod();
Any suggestions would be great!
Oh woops, completely overlooked that.
Static extension methods do not exist in C# (Unity or otherwise). This is by design.
Your best workaround is to simply create your own custom GameObjectEx class:
using UnityEngine;
using System.Collections;
public static class GameObjectEx
{
public static void DoSomething(GameObject target)
{
// Do something
}
public static void DoSomethingElse()
{
// Do something else
}
}
//elsewhere
GameObjectEx.DoSomething(myGameObject);
GameObjectEx.DoSomethingElse();
Sorry I donât quite follow.
I thought extensions have to be static.
CS1105: `MyExtensions.MyExtensionMethod(this GameObject, string)': Extension methods must be declared static
You define them with a âstaticâ keyword, but they are accessed like instance-level methods. Notice the âthis GameObjectâ; itâs providing the context of âthisâ. Static methods have no concept of âthisâ
So itâs possible to create an extension method that operates like this:
myGameObjectInstance.MyExtensionMethod();
But it is not possible to create an extension method that operates like this:
GameObject.MyExtensionMethod();
EDIT: thereâs more information here: Extension Methods - C# | Microsoft Learn
It touches on the static/instance nature of extension methods.