Extension methods
Forms that compile (4)
Section titled “Forms that compile (4)”| Syntax | Description |
|---|---|
ExtStaticHelpers.Twice(2) | Calling by type name |
public static int Twice(this int n) | Adding to a built-in type |
public static int Double(this ExtPoint p) | Adding to your own value type |
public static float Flat(this Vector3 v) | Adding to a runtime type |
Declaration and calling
Section titled “Declaration and calling”Calling by type name
Section titled “Calling by type name”using UnityEngine;using Tsukimi;
public static class ExtStaticHelpers{ public static int Twice(int n) { return n * 2; }}
public class ExtStatic : TsukimiBehaviour{ void Start() { Debug.Log(ExtStaticHelpers.Twice(2)); // => 4 }}Adding to a built-in type
Section titled “Adding to a built-in type”using UnityEngine;using Tsukimi;
public static class ExtIntHelpers{ public static int Twice(this int n) { return n * 2; }}
public class ExtPrimitive : TsukimiBehaviour{ void Start() { Debug.Log(2.Twice()); // => 4 }}Adding to your own value type
Section titled “Adding to your own value type”You can also add these to a struct you declare yourself.
using UnityEngine;using Tsukimi;
public struct ExtPoint{ public int X;}
public static class ExtPointHelpers{ public static int Double(this ExtPoint p) { return p.X * 2; }}
public class ExtStruct : TsukimiBehaviour{ void Start() { ExtPoint p = new ExtPoint(); p.X = 2; Debug.Log(p.Double()); // => 4 }}Adding to a runtime type
Section titled “Adding to a runtime type”You can also add these to types the runtime exposes. You can write these without having the type’s definition.
using UnityEngine;using Tsukimi;
public static class ExtVectorHelpers{ public static float Flat(this Vector3 v) { return v.x + v.z; }}
public class ExtEnvironment : TsukimiBehaviour{ void Start() { Debug.Log(Vector3.one.Flat()); // => runtime value }}