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
MediumAn 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 classFlatExtensions. FlatDistanceextends Vector3:a.FlatDistance(b)returns the distance fromatobacross the ground, leaving out the difference in height. From (0, 5, 0) to (3, 0, 4) it is 5.FaceFlatextends Transform:t.FaceFlat(target)turnstto 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 itseyesare on while the player is closer thansight(3) across the ground, and off otherwise. The owl sits high on its post, so this is notVector3.Distance.
Press Play, walk round the post and under the owl, then Check.
Try it yourself
using UnityEngine;
// FlatExtensions: FlatDistance and FaceFlat
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types