Lam Cao's Blog

A Journey in Game Dev


Month: October 2018

[Unity Tips] Use CompareTag instead of string.Equals

Comparing tags is a thing we all do in every game project at some point but not everyone seems to know about the existence of CompareTag. Unity could really have done a better job documenting this useful method.

In short, use obj.CompareTag("someTag") instead of string comparisions such as obj.tag=="someTag". CompareTag is much faster and will log an error if a tag is not defined, which is a very good thing.

In case of comparing against a list, use list.FirstOrDefault(t=>obj.CompareTag(t))!=null rather than something like list.Contains(obj.tag) for the same reasons.


A singleton utility for gameObjects

I use a fair number of singletons in my game projects. And I think I have written something similar the code block below for too many times now. So have you, probably.

void Awake() 
    if (instance == null)       
        instance = this;
    else if (instance != this)  

Getting tired of copy&pasting that code snippet over and over, I want to archive the same thing in just one line of code. When someone looks at my code, I want them to recognize the singleton pattern in less than half a second – “Oh hell, singleton again!”