Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Draw on top of collider handles in editor

Discussion in 'Editor & General Support' started by llamagod, Dec 25, 2019.

  1. llamagod

    llamagod

    Joined:
    Sep 27, 2015
    Posts:
    76
    Example code that draws a line on top of the top of a BoxCollider2D in a custom editor:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEditor;
    4.  
    5. [CustomEditor(typeof(SomeBehaviour))]
    6. public class SomeInspector : Editor
    7. {
    8.     public void OnSceneGUI()
    9.     {
    10.         var bounds = ((SomeBehaviour)target).GetComponent<BoxCollider2D>().bounds;
    11.         float z = 0f;
    12.         Handles.color = Color.blue;
    13.         Handles.DrawLine(new Vector3(bounds.min.x, bounds.max.y, z), new Vector3(bounds.max.x, bounds.max.y, z));
    14.     }
    15. }
    16.  
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. [RequireComponent(typeof(BoxCollider2D))]
    5. public class SomeBehaviour : MonoBehaviour
    6. {
    7. }
    8.  

    Draws on top of gizmos wireframe as it should regardless of component order:


    Does not draw on top of handles in edit mode if BoxCollider2D is placed below SomeBehaviour:


    How can I draw on top of handles in edit mode regardless of component order?
     
  2. llamagod

    llamagod

    Joined:
    Sep 27, 2015
    Posts:
    76
    In the editor, subscribe to SceneView.onSceneGUIDelegate/SceneView.duringSceneGui. It is called after OnSceneGUI and OnToolGUI, meaning it will draw on top of both.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. [CustomEditor(typeof(SomeBehaviour))]
    4. public class SomeInspector : Editor
    5. {
    6.     public void OnEnable()
    7.     {
    8.         SceneView.onSceneGUIDelegate += OnAfterSceneGUI;
    9.     }
    10.  
    11.     public void OnDisable()
    12.     {
    13.         SceneView.onSceneGUIDelegate -= OnAfterSceneGUI;
    14.     }
    15.  
    16.     public void OnAfterSceneGUI(SceneView sceneView)
    17.     {
    18.         var bounds = ((SomeBehaviour)target).GetComponent<BoxCollider2D>().bounds;
    19.         float z = 0f;
    20.         Handles.color = Color.blue;
    21.         Handles.DrawLine(new Vector3(bounds.min.x, bounds.max.y, z), new Vector3(bounds.max.x, bounds.max.y, z));
    22.     }
    23. }