Custom gizmos with OnDrawGizmos

Did you know that by implementing OnDrawGizmos() method in your scripts you can draw a custom gizmo?

Last time we talked about how to use icons’ settings to assign various icons to invisible game objects. Yet if you have some experience with scripting then you can create your own gizmos.

Basic Example

Gizmo drawing can be done using the Gizmos class. The most basic example will draw a red half-transparent cube in the place of current object.

After attaching this script to empty object it looks like this:

custom gizmo red cube

As you can see you can set up any size, position or color as you want, but usually it will be current transform.position. It’s a good practice to make your gizmos half-transparent to not cover any other visible scene elements. The other solution is to render the wireframe instead of a solid shape.

Selected Wireframe

Gizmos can be drawn all the times or only when the object is selected. You may consider the second option if your scene have many objects with gizmos and displaying gizmos of all object at any moment makes a little sense. To do that, you have to implement OnDrawGizmosSelected() method.

This one will be visible only when the object is selected. It is using DrawWireSphere() method to make the gizmo appear as wired sphere.

wired sphere gizmo

Tips

  • You’re allowed to draw as many gizmo objects in a single script as you want. Just add more than one Draw*() calls.
  • By settings Gismos.color to Color.clear you’re making the gizmo invisible, but it still can be selected just as it was visible

Files

As usual, you can download the example unitypackage here. Just double-click on it to import its contents into your Unity project. You will find there an example scene and the script from above.

related
IntermediateTips
Mobile Optimization – Unity Profiler
In the previous Mobile Optimization series post we talked about how important the batching...
2
IntermediateTips
Accessing Your Unity Game Logs
Unity allows you to log variety of messages into the Console window by using Debug.Log()...
1
AdvancedAugmented RealityTutorial
Corner and surface detection in AR Part 1
Introduction AR technology is getting more and more popular these days. Two big companies...
0
Call The Knights!
We are here for you.
Please contact us with regards to a Unity project below.



The Knights appreciate your decision!
Expect the first news soon!
hire us!