Menu
CoddyTech

Extension Methods

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 42 of 64.

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

Give the owl two extension methods.

  1. In FlatExtensions, add public static FlatDistance(this Vector3 a, Vector3 b): the distance without the height, 5 from (0, 5, 0) to (3, 0, 4).
  2. Likewise, FaceFlat(this Transform t, Vector3 target) turns t around y only.
  3. In Owl, face the player with FaceFlat; eyes are on while FlatDistance is below sight.

Press Play and walk under the owl: its eyes glow. Then Check.

Try it yourself

using UnityEngine;

public static class FlatExtensions
{
    // FlatDistance (Vector3) and FaceFlat (Transform) go here
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground