web analytics

Extension Methods in C# : Unity Scripting Tips

Extension Methods are a good way to add additional functionality to an existing class .Extension Methods can be made for built in classes or custom classes .

How to use Extension Method :

Lets say we have to set an Object and we want to set a tag for it , we can do that simply by using gameobject.tag= “Walls. What if you need a way to set the tag of a GameObject and all its children, but there’s no GameObject.SetTagRecursively()  available .

 

//Code

gameObject.tag=”Wall”;
foreach(Transform t in transform)
t.gameobject.tag= “Wall” ;

//Code

The above is fine , you can simply write that code whenever u need to set tag .But that is not the cleanest way to do it. Here comes the Extension Methods . Now we we will create an Extension Method for it .

extension methods in c# , extension methods in unity

It’s good to create a common class that contains all of your extension methods .So that you don’t look for the methods in every single class .

using UnityEngine;
using System.Collections;

public static class ExtensionMethods
{
    public static void SetTagRecursively(this GameObject gameObj, string tagName)
    {
        gameObj.tag = tagName;
        foreach (Transform t in gameObj.transform)
        {
            t.gameObject.tag = tagName;
        }
    }
}

Notice that the first parameter has the ‘this’ keyword followed by a GameObject variable .This variable denotes which class the extension method becomes a part of .

Now you simply have to call like this

gameObject.SetTagRecursively(“Wall”);
Extension methods are declared just like regular functions, except that they must be static and they must be declared inside a non-generic, non-nested, static class.
Though declared as Static ,this is invoked as if it were Instance method

You can see the Extension Method in intellisense

extension methods in c#

extension methods in c# , extension methods in unity

You can create you own extension methods for Transform .

e.g

transform.SetPositionX(2f);

Well it’s way much better than writing

transform.position = new Vector3(2f,transform.position.y,transform.position.z);

This is how you  can write Extension Method for it

using UnityEngine;
using System.Collections;
 
//Must be in a static class 
public static class Extensions
{
    public static void SetPositionX(this Transform t, float newX)
    {
        t.position = new Vector3(newX, t.position.y, t.position.z);
    }
}

 

extension methods in c# , extension methods in unity

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *