fafase
1
Unity has RequireComponent attribute to make sure the other component is there.
Also, this prevents the removal of the required component.
Would there be an attribute that prevents adding a component twice on an object?
I know I could do some kind of singleton process to remove a duplicate but in case there would be an easy way I am missing.
The attribute DisallowMultipleComponent
was just added in 4.5:
Introduced DisallowMultipleComponentAttribute for disallowing multiple components of the same type being added to a single GameObject.
[DisallowMultipleComponent]
public class Script : MonoBehaviour {
}
You could do it in the Awake of the component that should only be added once:
public class ThereCanBeOnlyOne<T> : MonoBehaviour {
protected void Awake() {
if(GetComponents<T>().Length > 1) {
Destroy(this);
}
}
}
public class SomeComponent : ThereCanBeOnlyOne<SomeComponent> {
}