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.

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.

related
BasicsTips
You can restore unsaved scene after Unity crash
Unity as any other software out there may crash from time to time. It's not a big deal unless...
1
IntermediateTips
Using the Unity Cache Server
  If you're working on a medium or big project then you may get into a situation...
4
IntermediateTips
Use decorator drawers to improve inspector view of your scripts
If you're writing a custom script then most probably you want to manipulate its public field...
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!