You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Extension Methods

Ben Liu
Ben Liu

Extension Methods are a feature that adding new methods to an existing class, which class is non-generic but static class. Similar to the extension concept in Swift.

Features of Extension methods:

  • Create a static class to include all the Extension methods we want to create
  • Extension methods are static
  • First parameter is this
  • We can only add methods but can't override methods

Example of Extension methods in Unity

using UnityEngine;
using System.Collections;


public static class ExtensionMethods
{
    //Notice that the first
    //parameter has the 'this' keyword followed by a Transform
    //variable. This variable denotes which class the extension
    //method becomes a part of.
    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);
    }
}

To use above extension methods:

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour 
{
    void Start () {
        transform.ResetTransformation();
    }
}

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp