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
Hide or lock layer in Scene window
Have you ever found yourself in a situation that the object you've put into the scene can...
0
BasicsTips
Use icons to see invisible object on scene
Your game scene may consist of objects that are visible on your scene view (like mesh) and...
0
AdvancedTips
MonoBehavior calls optimization
What if I told you that Unity can be wasting a lot of CPU performance just by calling your...
1
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!