How to use C# Method Extensions in Unity

Ever found yourself stuck working with the Transform or Vector3 types provided by Unity? Did it feel as if they lacked some functionality that would otherwise be useful to you? Did you feel compelled to wrap these functionalities into some kind of reusable Utility function? If your answer is yes to any of the questions above then we urge you to continue reading about how to use Method Extensions in Unity effectively.

What are Method Extensions?

Method Extenions are a powerful language feature that C# developers can use to extend the functionality of already existing classes and structs. Let’s have a look an example where we are adding an Method Extension to the UnityEngine.Vector3 struct:

Example of a Method Extension in Unity

  1. using UnityEngine;
  3. public static class Vector3Extensions
  4. {
  5. public static Vector2 xz(this Vector3 self)
  6. {
  7. return new Vector2(self.x, self.z);
  8. }
  9. }

The above code simply adds a new method to the UnityEngine.Vector3 struct that allows it to return its x and z components as a new UnityEngine.Vector2 struct. If this is your first encounter with an Method Extension then there are some things that might look a bit strange. Let’s break the above code down some more and explain the overall structure.

Method Extensions Structure

public static class Vector3Extensions

First of all, we need a static class that can actually group one or more Method Extensions together. All methods (or functions) in C# need to be contained within a class or struct. Now that we have declared a class to hold our Method Extension, we can start defining the method that we would like to extend it with.

public static Vector2 xz(this Vector3 self)

Actually declaring the Method is very similar to how you would normally declare a method inside a class. However, there is one small catch that we will get to in a moment. For now, let’s return to our code.

In our case, the method that we add onto the UnityEngine.Vector3 struct is called xz. It returns a structure of UnityEngine.Vector2 and takes in a structure of UnityEngine.Vector3. A careful observer will notice the usage of the keyword this just before the method parameter is declared. If you have been working with C# for a while then this might look a bit strange doesn’t it? (pun intented). So what is it? In this context it is referred to as a Parameter Modifier.

The Parameter Modifier

Without getting into much detail about Parameter Modifiers, it is important to point out that parameters in C# can have modifiers attached to them. These modifiers describe the way the values of the method. parameters are pushed into the method.

In our case, quite simply, the this modifier is nothing more than some added syntactic sugar. All you need to understand is that the parameter value is the actual class instance that calls the Method Extension. Next to that, It also infers the compiler to what type this new Method Extension should become available. Still unclear? Consider the following example:

Using our new Extension Method

Vector3 ballVelocity = new Vector3(1.0f, 2.0f, 3.0f);
Vector2 ball2DVelocity = ballVelocity.xz();

In the code above, we start by declaring a variable named ballVelocity. In our example this variable holds the velocity of a ball in 3 dimenions (x, y and z). On the next line, you will see that we can now use our newly created Extension Method xz() on the variable ballVelocity because it is of a type UnityEngine.Vector3. Since our Method Extension returns a UnityEngine.Vector2 we can now assign it to a variable of that type.

That’s it. There is nothing more to it.

Best Practices for Method Extensions

Now that you know how to use Method Extensions and how they work, we feel it is important to also share some best practices. These suggestions are mainly focused on the organization of the code throughout your project.

Grouping Method Extensions

Try grouping together Method Extensions that operate on the same type together. Following our example, we would add other extensions that operate on the UnityEngine.Vector3 struct into our Vector3Extensions class.

Placing Method Extensions inside a Namespace

Next to grouping similar Method Extensions together into a class, it is also beneficial to place the containing class into a namespace. In the example given, we could place the Vector3Extensions class into a namespace called Extensions. By doing this, we are able to ‘enable’ and ‘ disable’ the extensions simply by including (or not including) the Extensions namespace in our code.

namespace Extensions
	public static class Vector3Extensions {}

Common Pitfalls for Method Extensions

When starting to use Method Extensions for the first time there usually are a few common pitfalls that are good to point out. Let’s list these pitfalls below before you start experimenting.

Static Types

First off, it is only possible to use Method Extensions on instances. It is not possible to use Method Extensions on types alone. Therefore you will never be able to write method extensions in Unity along the lines of GameObject.InstantiateAfterDelay(1.0f) since there is no actual instance here that is being referred to.

Property Extensions

At this point in time, C# does not yet support adding extensions to classes and structs through the use of properties. If you want to extend a class you will have to use methods.

Tight Coupling

Similar to Utility methods, while creating Method Extensions it can become very tempting to build methods that simplify (sometimes almost automate) the programming work for you. This could create problems in your overall codebase where types are tightly coupled together. We recommend to limit your Method Extension to a maximum of 1 to 2 types.

Useful Method Extensions

Now that we have gotten you curious about creating Method Extensions, we urge you go have a look at some Useful Method Extensions that we have created ourselves. You can use these method extensions in your Unity projects and we try to update our extensions periodically.