- Home /
DisallowMultipleComponent and Generics
I found this on Unity docs:
(About DisallowMultipleComponent attribute) Prevents MonoBehaviour of same type (or subtype) to be added more than once to a GameObject
now if I have my classes
[DisallowMultipleComponent]
public abstract class Something<T> : MonoBehaviour { }
public class Concrete : Something<Whatever> { }
Unity won't allow multiple components of Something<Whatever>, what if I wanted to have only one Something?
It seems incredible you'd ever need to use Disallow$$anonymous$$ultipleComponent
as a beginner.
If for some reason you need to only ever have one, say, "Green$$anonymous$$onster" game object in a scene, just have a "watcher" script on a game object, which looks through the scene and checks you have only one.
Or, in the "Green$$anonymous$$onster" itself have a line of code that looks for other "Green$$anonymous$$onster" and alerts you if there is more than itself.
Well, I don't think it's good to have "editor only" Components ( #if UNITY_EDITOR
stuff, ecc...), anyway the Disallow$$anonymous$$ultipleComponent
solution is simpler and cleaner
Answer by brunocoimbra · Feb 02, 2016 at 04:26 PM
If you want only one something, make that:
[DisallowMultipleComponent]
public abstract class SomethingUnique : MonoBehaviour { /* Leave that class empty */ }
public abstract class SomethingGeneric<T> : SomethingUnique { /* Generic logic here */ }
public class Concrete : SomethingGeneric<Concrete> { }
Yes, you are right, I wrote the wrong answer, now I'll post a new one to keep this for the community.