I have an editor extension creates empty game object nodes. I show these in the scene view by using OnDrawGizmos event to Gizmos.DrawSphere at the correct location.
The documentation states that:
"Implement this OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn.
This allows you to quickly pick important objects in your scene."
But how do I actually detect that the sphere gizmo was picked?
After much digging around, I think I figured out how this works. Hopefully this will save somebody else some pain.
The OnDrawGizmos is only available to MonoBehavior objects. Unity therefore selects whichever game object that the component containing the OnDrawGizmos method is attached to. If you draw a number of gizmos within that OnDrawGizmos method, it is up to you to figure out which specific gizmo was picked, but that can’t be done inside the OnDrawGizmos because you don’t have access to the editor functions you need to make it work.
For me, that means I need to first attach a collider to the same object that the OnDrawGizmos method is attached to. Set the parameters to zero so they don’t interfere with normal processing. E.g. if you’re using a sphere, set the radius to zero.
Then, in my OnSceneGUI editor script:
- Check for Event.current.type == EventType.MouseDown
- Make a ray for the editor. E.g. Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition)
- Loop through each gizmo that was drawn.
- Set the collider to the same position and radius (in the case of a sphere).
- Call collider.Raycast using the editor camera ray to see if you hit it.
Fast and easy way is to just assign an icon (which can be an invisible texture) to the gameobject rendering your gizmo. This way you will select it on click.