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
AdvancedTips
How to Implement a Game Cheats Subsystem Within Unity3D
When you're creating a game, you have to play it again and again, repeat some scenarios or...
2
IntermediateTips
Console log can show you which object is the creator
Most probably you already know about Debug.Log() function and its variations, but did you know...
1
AdvancedGuide
Artificial locomotion in Unity using Machine Learning Part 3
Training and results ML-Agents training One of the most essential parts of training is hyperparameter...
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!