Menu
CoddyTech

Extension Methods

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 33 of 50.

Vector3 and Transform belong to Unity, so you cannot add a method to them. An extension method is a static method that C# lets you call as if it were theirs. These two save lines that come up in every project:

public static class UnityExtensions
{
    public static Vector3 WithY(this Vector3 v, float y)
    {
        return new Vector3(v.x, y, v.z);
    }

    public static void DestroyChildren(this Transform parent)
    {
        foreach (Transform child in parent)
        {
            Object.Destroy(child.gameObject);
        }
    }
}
// in any script
transform.position = transform.position.WithY(0.5f);
inventoryPanel.DestroyChildren();

Three things make an extension method: a static class that is neither nested nor generic, a static method, and this before the first parameter. That parameter is the value on the left of the dot, so transform.position.WithY(0.5f) compiles to UnityExtensions.WithY(transform.position, 0.5f). Vector3 is a struct, so v is a copy: WithY cannot change the caller's vector and returns a new one instead. That is also how it gets round transform.position.y = 0.5f;, which does not compile.

The static class is not a MonoBehaviour. It lives in a .cs file of its own, any name will do, and never goes on an object. Methods a MonoBehaviour inherits, such as Destroy, need their class here: Object.Destroy. Destroying children inside the foreach is safe, because Unity removes them only at the end of the frame.

challenge icon

Challenge

Medium

An owl on a tall post watches the yard. The arrows walk the Player (ready). Give the project two extension methods and use them in the owl:

  • In FlatExtensions.cs, write a static class FlatExtensions.
  • FlatDistance extends Vector3: a.FlatDistance(b) returns the distance from a to b across the ground, leaving out the difference in height. From (0, 5, 0) to (3, 0, 4) it is 5.
  • FaceFlat extends Transform: t.FaceFlat(target) turns t to face the target around y only, so it stays upright however high or low the target is.
  • In Owl.cs, every frame, the owl faces the player with FaceFlat, and its eyes are on while the player is closer than sight (3) across the ground, and off otherwise. The owl sits high on its post, so this is not Vector3.Distance.

Press Play, walk round the post and under the owl, then Check.

Try it yourself

using UnityEngine;

// FlatExtensions: FlatDistance and FaceFlat
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity