Extension Methods in Unity

Aaron Grincewicz
3 min readJul 24, 2022

--

Throughout the past two years I have been using and learning Unity, I’ve found myself repeatedly using certain methods and techniques. Sometimes, it’s easier to streamline the process and create a method for whatever code you are repeating. Now, you could create a static class along with some static methods that you can call where you frequently use that functionality… Or, you could add some of those shortcuts to what already exists in Unity with extension methods.

One thing I find myself doing repeatedly is setting the transform position of a game object that I’ve instantiated to the position of the spawner. Normally, you would do something like this:

In a real game, you’re writing this code several times in different classes. With an extension method, you write it once and then use your shortcut from that point on.

For the example above, I’ve added an extension method called “MatchPosition” to the Transform component. It takes the game object you’d like to match the position of as a parameter and sets the position of the object you specify to… wait for it… match that position. This extension method can be used whenever you use the Transform component.

The Extension Method declaration.
‘MatchPosition’ Extension Method implementation.

Another example of extending the Transform component is the “OffsetPosition” method I’ve added.

‘OffsetPosition’ Declaration.
‘OffsetPosition’ Implementation.

Normally I would have the offset Vector3 as a variable, but for this example I’ve just set a new Vector3 as the parameter. Now, anything with a transform component can have its position offset with less code.

You don’t need to think of completely original and genius ideas to make extension methods useful. Having a few quick shortcuts can make your code cleaner and easier to read.

Does your game have a health bar, or image in which you set the fill amount to show progress, etc...? Why not add an extension method to the Image component and set the fill without typing something like (image.fillAmount = health/100.0f;) over and over?

SetFill Implementation
‘SetFill’ Implementation.

I say have fun with it. Find out what will save you time and go from there.

Declaration of FillTimerRoutine Extension Method

In the code above, I am having some fun with a timer extension method. Now, I can use this for something like a Timer UI element and call it with something like:(StartCoroutine(image.FillTimerRoutine(1.0f, 0.0f,60.0f,5.0f, false))). That will start the coroutine extension method to increment the fill amount of the image by 12 percent(?)… every second.

--

--