C# Extension Methods

Hi Guys,

Is it possible to do C# Extension methods in unity? :face_with_spiral_eyes:

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.

Thanks