Extension Classes – Unity

So these are classes that you write, that extend one of the Unity classes. There’s a good example on one of the Learn Unity tutorial site here. But basically  you will create the class file like this:

using UnityEngine; 
using System.Collections; 

    //It is common to create a class to contain all of your 
    //extension methods. This class must be static. 

    public static class ExtensionMethods
{
    //RULE 1 : extension methods must be declared static. 
    //RULE 2 : The first parameter must have the keyword "this"
    //RULE 3 : Follow the "this" with the Class name that you are extending, 
    // example, Vector3, Transform, Rigidbody
    //RULE 4 : Follow the class type with a variable name to use in the method
    // then just do whatever you need to in the method as per usual

    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);

    }

}

Now you can refer to your new extension method with the following code

//Notice how you pass no parameter into this
//extension method even though you had one in the
//method declaration. The transform object that
//this method is called from automatically gets
//passed in as the first parameter.
transform.ResetTransformation();

it is the same as saying

ExtensionMethods.ResetTransformation(yourTransform);