Today we are going to learn something entirely new! Extension Methods!
Sometimes as you are developing a game, you have this idea in your mind that you wish you could add some more functionality to Unity Components.
With
But how do they work?
Extension methods
Implementation
To show you how they look like, let’s create an extension to the Transform, which will return the list of its children.
using System.Collections.Generic; using UnityEngine; /// <summary> /// This class contains extensions to the Transform class. /// </summary> public static class TransformExtensions { /// <summary> /// Gets all children of tranfsorm and returns them. /// </summary> /// <returns>List of childern.</returns> /// <param name="transform">Transform.</param> public static List<Transform> GetChildren(this Transform transform) { var children = new List<Transform>(); // Iterate over all children in transform. foreach (Transform child in transform) { children.Add(child); } return children; } }
You might notice that the first parameter is little different than regular as it has “this” keyword. This points to the object from the method will be called.
As we have some knowledge, let’s make an extension to the String class to generate random text with provided length.
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// This class contains extensions to the string type. /// </summary> public static class StringExtensions { /// <summary> /// Adds random text at the end of a string. /// </summary> /// <returns>Enlarged text with random symbols at the end.</returns> /// <param name="s">String.</param> /// <param name="amount">Amount of new symbols.</param> public static string AddRandomText(this string s, int amount) { string rt = string.Empty; for (int i = 0; i < amount; i++) { rt += (char)Random.Range(65, 91); } return s + rt; } }
Example
So let’s see how we can use them in action!
By using both extensions, we can iterate over all children of the GameObject and then change their names to the name of the GameObject with some random ending.
using UnityEngine; /// <summary> /// Example of use for class extensions. /// </summary> public class Example : MonoBehaviour { /// <summary> /// Unity method called on the first frame of the game. /// </summary> void Start() { var children = transform.GetChildren(); foreach (var child in children) { child.name = name.AddRandomText(10); } } }
Coding was easy! Now let’s see if it’s working?
Yeah! It’s working! ?
Other examples
Of course, there is already a lot of repositories with examples. Like
My extensions are also available in my public repository if you want to check them out. ?
If you want to continue reading, I’ve recently published two posts about extending the Unity Editor to suit your needs better. Those are Custom Windows in Unity and Custom Inspector in Unity.
Hope you enjoyed and see you next time! ??