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
MediumGive the owl two extension methods.
- In
FlatExtensions, add public staticFlatDistance(this Vector3 a, Vector3 b): the distance without the height,5from (0, 5, 0) to (3, 0, 4). - Likewise,
FaceFlat(this Transform t, Vector3 target)turnstaround y only. - In
Owl, face the player with FaceFlat;eyesare on while FlatDistance is belowsight.
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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground