Unity Useful Snippets

I made this post to compile some of useful snippets that I frequently use in my coding. So instead of searching around again and again, I better to list them here in one place.

How to set object tag by script in Unity

This one apparently so simple. To set a tag of a game object, for example I have game object: “myobject”, I can set its tag by typing: myobject.tag = newtag.

How to convert Unity raw image texture to Texture2D

Let’s say we have a raw image object in our Unity canvas, and we want to convert it’s image to Texture2D. Here is what we do on our scripting: First we declare a texture2d variable, for example: Texture2D myt2d; And then, we grab that raw image game object’s texture (let’s say we have myrawimage as the Raw Image) this way: myt2d = myrawimage.texture as Texture2D; And that’s all, we have our myt2d ready to use.

How to instantiate an object then access a script attached to it or call a function in that script

We can do it this way:

GameObject myobject = (GameObject)Instantiate(Resources.Load("myobject"));
myobject.GetComponent<SomeScript>().textValue = "Hello World!";

To check and uncheck / hide or show a layer mask in camera culling mask by script:

Camera camera = GetComponent<Camera>();
camera.cullingMask &=  ~(1 << LayerMask.NameToLayer("Avatar")); //hide Avatar layer
camera.cullingMask |= 1 << LayerMask.NameToLayer("Avatar"); //show Avatar layer

How to get local ip address:

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

How to destroy all game objects with a specific tag

For example if we have objects with tag “enemies” we can destroy them all by calling this method:

Destroy(GameObject.FindWithTag("enemies"));

EDIT: above method is not working, it will only destroy the first game object with tag. We need to do for each loop instead:

GameObject[] objs = GameObject.FindGameObjectsWithTag("xxx");
foreach (GameObject obj in objs)
        {
            Destroy(obj);
        }

Leave a Reply

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