Extend GameObjects with custom methods

Being able to add custom methods to GameObjects can really make your code more readable.

In cases when something happens to an object and there can be multiple outcomes, like when a GameObject collides with another GameObject, I sometimes find my self writing code like this:

Friend friend = gameObject.GetComponent<Friend>();
if (friend != null) {
    // Do something nice
}

Foe foe = gameObject.GetComponent<Foe>();
if (foe != null) {
    // Do something bad
}

Of course, there might be many ways of solving this in better ways. Let's for the sake of the example stick with it.

With the help of extension methods, this piece of code can be written like this:

if (gameObject.isFriend()) {
    // Do something nice
}

if (gameObject.isFoe()) {
    // Do something bad
}

You may have noticed that I have just used two functions that doesn't normally exist on GameObject. So, how do we extend GameObjects with our own functions? Do like this:

public static class GameObjectExtensions {

    public static bool isFriend(this GameObject go) {
        if (go.GetComponent<Friend>()) {
            return true;
        }
        return false;
    }

    public static bool isFoe(this GameObject go) {
        if (go.GetComponent<Foe>()) {
            return true;
        }
        return false;
    }
}

Create a static class without extending any other class, and add publicly available static methods for each function you want to extend GameObject with. The trick is in the method parameters. Notice the use of the this keyword. That's all there is to it.

There's more info on C# extension methods to be found on Microsoft's page Extension Methods.

Latest articles