I’ve recently come up with a couple of situations where Extension Methods have been useful when coding in Unity3D. This is intended to be a rough introduction with some practical examples for how to make your life easier. Lets start by talking about
Enhancing Assets from the Asset Store
I’ve been getting more and more things from the Unity Asset Store.
But, imagine the situation where you get a tool that does just not quite what you want, or a little change would make your life a lot easier; or you have encountered a bug.
Usually, you are going to get source access to the scripts when you download something, so you are free to modify them, but even then this presents a problem: When you update to a new version, you’ll lose your changes and have to merge to the new update. a bit of a pain.
We can solve this problem using Extension Methods. By using Extension Methods we can add methods to another object without changing the original file. Let’s work an example.
Recently, I’ve been using the marvelous 2D Toolkit For our last game RollRover, I cut up and managed a sprite atlas myself which ended up taking an inordinate amount of time. 2DToolkit takes away all that pain and then some. It’s well worth checking out.
But, changing the text on a tk2dTextMesh object can be a bit annoying, because you have to do two calls.
someMesh.text = "Hello World!";
someMesh.Commit();
The author provides a good reason for this, It means you can change multiple properties, for example, the colour and the text, and not have to calculate the mesh twice, but sometimes, i just want to change the text, and i know i that’s all I’m going to do, and i don’t want to have to call Commit() every time.
So, using extension methods, I can add a new SetText method to the tk2dTextMesh class, so i only have to write one line when calling. I tend to make a new file for extension methods called ExtensionMethods.cs ; you can keep them wherever you want or put them over multiple files as it pleases you. Here is what it looks like:
internal static class ExtensionMethods
{
public static void SetText(this tk2dTextMesh mesh, string newText)
{
mesh.text = newText;
mesh.Commit();
}
}
With this code in place, you should see a new method available, on the tk2dTextMesh class, even though there is no such method in that class.

Neato! So how does it work? Let’s break it down.
internal static class ExtensionMethods
The only important particularly important thing here, is the static modifier, the class name doesn’t matter, and you can have it public or internal so long as you can access it from wherever you are calling, but extension methods must be declared in a static class.
public static void SetText(this tk2dTextMesh mesh, string newText)
The important bit here the this keyword. this (at least in this context) is the hint to the compiler that its an extension method, not a regular method. When you call the method, the first parameter is implicit you only provide the second parameter onwards. Underneath, whatever object you actually called the method on is passed in, we’ll see that later.
mesh.text = newText;
mesh.Commit();
with that passed in we can now act on the mesh object, in this case we’ll set the text to the second parameter, newText and call Commit()
Now, setting the text is a simpler call:
someMesh.SetText("Hello World!")
When we call SetText, control will flow into the extension method, passing in someMesh as the first parameter, and the method will set the text to the new value and commit the change. Cool.
There is a bunch of neat stuff you can do with this. Another example using 2D Toolkit is setting a sprite – You have to set a sprite to a spriteID but to get the spriteID for a given asset name, you need to call GetSpriteIdByName With extension methods again, you can collapse this down to a single call:
public static void SetSpriteTo(this tk2dSprite sprite, string spritename)
{
var spriteID = sprite.GetSpriteIdByName(spritename);
sprite.spriteId = spriteID;
}
someEnemy.SetSpriteTo("Dead");
Improving UnityEngine
Just like you can change things in the asset store without using the source, You can also use this for things that arent quite filling expectations in UnityEngine without even having the source, take FindObjectOfType. a while ago, Unity added a generic implementation of GetComponent but neglected to to do so for FindObjectOfType
The result is having to write an ugly line like:
statTracker = (LevelStatTracker) FindObjectOfType(typeof(LevelStatTracker));
again, with Extension methods we can do better. Lets add a generic version onto UnityEngine.Object
public static T FindObjectOfType(this Object obj) where T: Object
{
return (Object.FindObjectOfType(typeof (T)) as T);
}
Here we take a generic argument of Type T and return an object of Type T meaning now when you need to find an object of a type, you can simply call it right in the monobehaviour
statTracker = this.FindObjectOfType
Another cool thing is that, as users of C# in unity will know, this won’t work:
myGameObject.transform.position.x = 5f;
The reason you can’t do this is that position is a value type, so you would only be editing a copy – useless. But still, this can be a real pain, if you want to just change the x to a defined value you’ll have to do:
gameObject.transform.position = new Vector3(
5f,
gameObject.transform.position.y,
gameObject.transform.position.z);
which is kinda verbose. So, what we will do is add an Extension Method on the Transform component to let us set it in one line. Here is what the extension method looks like:
public static void SetX(this Transform trans, float x)
{
trans.position = new Vector3(x,trans.position.y,trans.position.z);
}
which allows us to set our X much easier:
gameObject.transform.SetX(5f);
Other Cool Stuff
Extension Methods can also be used to make fluent interfaces. generally speaking, I hate these, but used sparingly it can make some things much nicer.
For example In the current 2D game I’m working on, I often want to say, i want to say: “move this object over here for x and y, but not for z, use this value for z.” This manifests in code like this:
buttonOverlay.transform.position = new Vector3(
button.transform.position.x,
button.transform.position.y,
5f);
It can be a bit of a pain because that is quite a common operation.
So using extension methods i can extend the Vector3 struct to make my life easier:
public static Vector3 OnLayer(this Vector3 vector,float layer)
{
return new Vector3(vector.x,vector.y,layer);
}
So, this is an extension method which attaches to Vector3, and returns a new Vector3 with the first parameter’s X, the first parameter’s Y and the second parameter’s Z. Moving an item is now much cleaner!
buttonOverlay.transform.position = button.transform.position.OnLayer(5f);
The idea with a fluent interface is we can create things that read really fluently, in this case it does “Put it at this position on layer X”. Taking the idea further, if we extend Transform with a few extension methods that return the same Transform We can make some operations more fluent
transform = button.transform.OnLayer(5f).WithRotation(Quaternion.Identity).ScaledBy(2f);
Note that fluent != better. I wouldn’t do the above example myself. it violates POLA and I’d count it as misuse/overuse of extension methods.
Closing Words
Extension methods are cool, but I’ve seen them misused. They are particularly useful when you don’t have access to the source, or the source is otherwise hard to modify. But (imo) it should be a tool in your box rather than some standard development practice.
Also, in the example of adding a SetX method to the Transform component you might be tempted to add a SetX method to Vector3; but you may end up scratching your head over why it doesnt work. With Vector3 being a value type, we are actually passed in a copy on the extension method, and modifying it will do precisely nothing; Just a gotcha to look out for.
Finally there is nothing really magical about Extension Methods that mean you can do something that you couldn’t do before, but it just makes some things make a bit more sense.