Extension Methods in Unity

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 extension methods, you can do that! ?

But how do they work?

Extension methods are mostly used when you have existing classes, but you can’t edit them, just like in Unity. With them, we can add more functions that will make our lives easier.

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.

Our extension is now part of the Transform!

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?

Editor view (left) and Play mode (right)

Yeah! It’s working! ?

Other examples

Of course, there is already a lot of repositories with examples. Like omgwtfgames/A set of Unity3D extension methods or dracolytch/DracoSoftwareExtensionsForUnity, but it’s always good to know what code in your project do! ?

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! ?‍?

5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x