17 Jul 2015

Custom gizmos with OnDrawGizmos

Piotr Korzuszek
By Piotr Korzuszek Unity Development Expert

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.

using UnityEngine;

public class GizmoCube : MonoBehaviour {
    void OnDrawGizmos() {
        Gizmos.color = new Color(1, 0, 0, 0.5f);
        Gizmos.DrawCube(transform.position, new Vector3(1, 1, 1));
    }
}

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.

using UnityEngine;

public class GizmoSphere : MonoBehaviour {
    void OnDrawGizmosSelected() {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, 2);
    }
}

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.

Piotr Korzuszek
By Piotr Korzuszek Unity Development Expert
SIRBart

Call The Knights!

    Table of contents