Oftentimes you’ll find yourself using classes you can’t modify. Whether they’re basic data types or part of an existing framework, you’re stuck with the functions that are provided. That being said, C# provides a nifty trick to appending functions to classes! These are known as Extension Methods.
Extension methods are fairly simple to create and are frequently used as syntactic sugar. A practical example can be seen with Unity’s Transform class. Let’s say you want to set only the x variable of Transform.position.
|
In this case Transform.position gives you an error if you only try to assign its x member variable, so you have to assign the entire Vector3. An extension method such as SetPositionX() could be appended to the Transform class and help make this code more readable.
In order to create extension methods you have to create a static class. In addition, an extension method declaration must be declared static and have the first parameter be of the type that you’re writing the method for, preceded by the this keyword.
|
Now you can go back to your other script and replace our old code with the new extension method.
|
NOTE: Extension methods can only be called on an instance of a class, not on the class itself.
Here are a few more extension methods to get you started, as well as an example script that utilizes a few of them.
Extensions:
|
Example Script:
|
NOTE: Static classes do NOT extend MonoBehaviour.
ANOTHER NOTE: If you define your extension methods inside of a namespace, you have to declare the use of that namespace in order to bring them into scope.