Thursday, June 2, 2011

Unity: Locator.cs

My first code example! It shows how I draw the custom gizmo for the Locator game object (an empty game object which I use to define nodes such as waypoints or spawnpoints). Not very exciting, but this was one of the harder things to find in my googling, so if a beginner like me stumbles across this page and has a bit of a lightbulb moment, it'll be worth it!

The OnDrawGizmos() MonoBehaviour override is, as the name suggests, the method in which to place Gizmo drawing, as it's called automatically by the editor, but not during the game. I believe there's also an OnDrawGizmosSelected() method which you can use to draw a custom gizmo when the entity is selected.

Just drag this MonoBehaviour onto an empty game object to create a visible locator. Easy as that :) Best of all: You can select the entity by clicking the gizmo!

Unity is so clever, amiright?

// Basic Locator object
public class Locator : MonoBehaviour
{
 // Draw Gizmo
 void OnDrawGizmos()
 {
  Vector3 pos = transform.position;
  Vector3 scl = transform.localScale;
  Vector3 posX = new Vector3(pos.x + scl.x, pos.y, pos.z);
  Vector3 negX = new Vector3(pos.x - scl.x, pos.y, pos.z);
  Vector3 posY = new Vector3(pos.x, pos.y + scl.y, pos.z);
  Vector3 negY = new Vector3(pos.x, pos.y - scl.y, pos.z);
  Vector3 posZ = new Vector3(pos.x, pos.y, pos.z + scl.z);
  Vector3 negZ = new Vector3(pos.x, pos.y, pos.z - scl.z);
  
  Gizmos.color = Color.white;
  Gizmos.DrawLine(posZ, negZ);
  Gizmos.DrawLine(posY, negY);
  Gizmos.DrawLine(posX, negX);
 }
}

No comments:

Post a Comment