Search Unity

GetComponent in an editor script.

Discussion in 'Immediate Mode GUI (IMGUI)' started by Stone-Legion, Feb 8, 2016.

  1. Stone-Legion

    Stone-Legion

    Joined:
    Aug 16, 2013
    Posts:
    112
    I was using public variables in an Editor extension script, however, I ran into serialization errors and then read that this is not a supported feature of Unity after it was discontinued several versions ago.

    I want to be able to get the components of a Transform that an editor script is attached to so I can draw a wire radius within the editor.

    I have the following code but obviously (MonoBehaviour)target will not work because it is only for selected GameObject in the hierarchy. I want this to draw the wire lines in the editor even when it is not selected.

    Does anyone have any suggestions?


    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEditor;
    4.  
    5. [CustomEditor(typeof(MobSpawner))]
    6. class MobSpawnerEditor : Editor
    7. {
    8.  
    9.     void OnDrawGizmos()
    10.     {
    11.         MobSpawner connectedSpawner= ((MonoBehaviour)this.target).gameObject.GetComponent<MobSpawner>();
    12.         if (connectedSpawner== null)
    13.             return;
    14.         Gizmos.color = connectedSpawner.editorWireColor;
    15.         if (connectedSpawner.scanForPlayerShape == ScanType.Cube)
    16.         {
    17.             Gizmos.DrawWireCube(connectedSpawner.transform.position
    18.                 , new Vector3(connectedSpawner.scanForPlayerHalfExtentsCube.x * 2, connectedSpawner.scanForPlayerHalfExtentsCube.y * 2, connectedSpawner.scanForPlayerHalfExtentsCube.z * 2));
    19.          
    20.         }
    21.         else if (connectedSpawner.scanForPlayerShape == ScanType.Sphere)
    22.         {
    23.             Gizmos.DrawWireSphere(connectedSpawner.transform.position
    24.                 , connectedSpawner.scanForPlayerRadius);
    25.         }
    26.  
    27.     }
    28.  
    29. }
    30.  
     
  2. appslabs

    appslabs

    Joined:
    Aug 5, 2013
    Posts:
    121
    How about
    Code (CSharp):
    1. GameObject go = Selection.activeGameObject;
    2.  
    and getting components from it?
     
    Ferb and Ak47-forever like this.
  3. skalev

    skalev

    Joined:
    Feb 16, 2012
    Posts:
    264
    OnDrawGizmos is not for an editor script.

    you should add this function to your MobSpawner script, and it will draw the gizmos for every MobSpawner in the scene. This will eliminate the need to call GetComponent<MobSpawner>()