Unity tip for the day: Always name your new GameObject()s

So, just to be clear, although I have done two tips in so many days, does not mean that I will necessarily be putting a tip up every day. Just since I am hip-deep in Unity at the moment, I am posting some little things that come to mind as I am coding along here. (currently working on the new xTUIO Unity presentation thingy, also, looking at version 1.1 of Snowferno, and! we are staring a new iPhone game in Unity: currently known as “Game B”.. so using Unity quite a bit at the moment)

Anyway, tip for today: always Always ALWAYS name your generated objects.

So you have a little bit of code like so:

                if (pivot == null) {
			pivot = new GameObject();
			pivot.transform.position = gameObject.transform.position;		
			pivot.transform.localScale = gameObject.transform.lossyScale;
		}

And that is great, and it works fine. When you run this code you will have a nice object pop up in your hierarchy called “New Game Object”. This is fine if you do this once. But generally you are scripting in order to be able to do lots of stuff at once. So say you have a few dozen objects that all need a pivot, so then you you get a scene hierarchy like this:

Picture 71

Not very useful really. And if you are like me, and try to make everything all nice and objecty, the pivot generating code is somewhere high up in the class tree and there are three or four different classes of object that are using this code, so you have no idea really which one is making them (and not destroying them as intended, or whatever)

Instead just add a single line in there:

                if (pivot == null) {
			pivot = new GameObject();
			pivot.name = "Pivot " + gameObject.name; // Name it!
			pivot.transform.position = gameObject.transform.position;		
			pivot.transform.localScale = gameObject.transform.lossyScale;
		}

This will make debugging much much easier. Anyway, it seems like a simple thing, and it is, but I find myself forgetting to add it in until I have a problem, then I have to spend 20 minutes finding all the places that I generate new objects and adding in a ‘name’ line. So get in the habit of naming your generated obejcts and your debugging life will become much happier!

note: this is good advice for any object in the unityverse. not just empty game objects. if you are generating any kind of component or camera or whatever, just spend the 2 seconds it takes to give it some name… trust me..

Cheers!
-B

This entry was posted in Blog, code, multitouch, Unity. Bookmark the permalink.

Leave a Reply