Search Unity

Is there a way to automatically prevent redundant monobehaviours (a la colliders?)

Discussion in 'Scripting' started by teatime, Mar 23, 2011.

  1. teatime

    teatime

    Joined:
    Jun 16, 2008
    Posts:
    129
    When you try to add a Collider to a GameObject that already has one, Unity won't let you. Is there any way to put the same restrictions on a custom MonoBehaviour? Right now I'm doing some pretty hacky stuff in the MonoBehaviour's Awake() to work around it in play mode, but it'd be nice if I could just stop it from ever happening, especially within edit mode. There really ought to be an attribute for it (maybe something for the wish list.)
     
    Last edited: Mar 23, 2011
  2. teatime

    teatime

    Joined:
    Jun 16, 2008
    Posts:
    129
    well, i got my hack good enough that i'm happy with it, although it will only work if you can get away with using [ExecuteInEditMode]. here it is, if anyone wants it:

    Code (csharp):
    1.  
    2.  
    3. [ExecuteInEditMode]
    4. public class MyMonoBehaviour : MonoBehaviour {
    5.  
    6. void Awake ()
    7.     {
    8.         MyMonoBehaviour[] localInstances = gameObject.GetComponents<MyMonoBehaviour>();
    9.        
    10.         if (localInstances.Count() > 1) {
    11.                 Debug.Log ("Can't add component 'MyMonoBehaviour' to " + this.gameObject.name + "because such a component is already added to the game object!");
    12.             StartCoroutine(DestroyNextFrame());
    13.            
    14.         }
    15.         else
    16.         {
    17.             //whatever you'd do otherwise
    18.         }
    19.     }
    20.    
    21.     IEnumerator DestroyNextFrame ()
    22.     {
    23.         yield return 1;
    24.         DestroyImmediate (this);
    25.     }
    the use of a coroutine seems necessary to prevent this apparently harmless but annoying error that obscures the Debug message:

    Code (csharp):
    1. m_InstanceID == 0
    2. UnityEditorInternal.InternalEditorUtility:InspectorWindowDrag(Object, Boolean)
    3. UnityEditor.DockArea:OnGUI()
     
    Last edited: Mar 23, 2011