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.)
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:
[ExecuteInEditMode]
public class MyMonoBehaviour : MonoBehaviour {
void Awake ()
{
MyMonoBehaviour[] localInstances = gameObject.GetComponents<MyMonoBehaviour>();
if (localInstances.Count() > 1) {
Debug.Log ("Can't add component 'MyMonoBehaviour' to " + this.gameObject.name + "because such a component is already added to the game object!");
StartCoroutine(DestroyNextFrame());
}
else
{
//whatever you'd do otherwise
}
}
IEnumerator DestroyNextFrame ()
{
yield return 1;
DestroyImmediate (this);
}
the use of a coroutine seems necessary to prevent this apparently harmless but annoying error that obscures the Debug message:
m_InstanceID == 0
UnityEditorInternal.InternalEditorUtility:InspectorWindowDrag(Object, Boolean)
UnityEditor.DockArea:OnGUI()