(Editor) Insure that a GameObject can only have one Component of type <Type> attached

Hey all,

I am trying to add some structure and do some fool-proofing with a system I am constructing.

What I am aiming to achieve is to insure that if a Game Object already has a Component of type attached, it will not allow you to add another of . I would like this to occur at author-time in the Editor when the user either drags the script onto a Game Object or adds it via the Components menu. I already have a method of detecting the user's problem at run-time.

I would expect this to work with inheritance, which is a large part of this system. (ie if a Game Object already has an attached Component < B >, which extends < A >, you would not be allowed to add a component < C >, which also extends < A >. Furthermore, you would be prevented from adding any Component that ever inherits from < A >.)

This feature would be similar to what happens when a Game Object already has an attached , but you attempt to add, for example, a SphereCollider to it.

To reiterate, I do have a way of notifying the user of their mistake at run-time, but I would like to be able to, if possible, prevent the mistake from ever happening at author-time.

I am assuming that there would be something like the Attribute RequireComponent(), but is either hidden or undocumented in the API reference.

If someone could point me in the right direction of an Attribute or another method of doing this, it would be much appreciated.

Thanks in advance,


I’m not sure how recently this was added, but there is now the class attribute:


This will prevent the editor from letting the user add the Component to the same GameObject twice.

In your Awake() function, or alternatively in whatever code is trying to attach the script to the object, simply do a GetComponent() call. If it returns something, then you know it's already on there, if it returns null you know there isn't one already and can place the script there.

Awake function example:

void Awake()
    ScriptA temp = GetComponent<ScriptA>();
    if(temp != null)

Adding from another script example:

void AddScript(GameObject objToAddTo)
    ScriptA temp = objToAddTo.GetComponent<ScriptA>();
    if(temp == null)
        Debug.Log("ScriptA was already on the object!");

NOTE : I haven't tested these scripts, just wrote them straight in here, but they should put you on the right path.