Drawing custom Gizmos in Unity

Screen Shot 2016-02-06 at 8.56.16 PM.png

I will avoid making a custom Editor script by any means necessary.

Did you know you can easily draw your own Gizmos for the scene view using a simple magic method? I sure didn’t. I had to create a tree visualization structure for the editor for the game I’m working on, and I was dreading the day I would have to get into Editor scripting just for this tiny thing.

Luckily, I don’t have to!

The magic method void OnDrawGizmos() and void OnDrawGizmosSelected() is all I needed to get this effect. OnDrawGizmos() is like an Update() function for when you’re inside the scene view. The “selected” variant is the same thing, except that it’ll only run if the object is selected in the editor.

In my OnDrawGizmos() function, all I did was loop through all child nodes and draw 9 lines for each. Why 9? Well, one line is to connect the two, and the 8 remaining lines are to draw the little arrow thing. There’s a way to use Handles.ArrowCap() to do the arrow drawing, but I like the wireframe look.

In the sample code below, you can see the rough structure (and a good one) to handle the drawing you see above. The DrawConnectedGizmos() function is nicely separated—all that does is do the maths for the arrow drawing. I used a very helpful script for the arrow drawing here.

Screen Shot 2016-02-06 at 9.02.07 PM.png

I put this as an image so you can’t copy and paste it.

For the text on each GameObject, I used the Handles.Label(Vector3, string) method. It’s rather straightforward. Just put the place you want the text to appear as the first argument, and the text you want to display in the second.

Once you finish, you’ll gasp at the results! Or at least I will.

One thought on “Drawing custom Gizmos in Unity

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s