How to make RequireComponent list possible options.

If you specify [RequireComponent(typeof(Collider))] for a MonoBehaviour, once you try adding it, you will get a message:

Adding component failed. Add required component of type ‘MeshCollider’ or ‘BoxCollider’ or [snip] to the game object ‘Your Object’ first.

I would like to have a similar message for one of my own components. I have an interface that is implemented by multiple classes and I would like to list them there. If I try using my interface with RequireComponent, I get a message that says that script class can not be abstract. If I have a concrete base class with RequireComponent, than it is simply added, which is not what I want. I would like to prompt user that one of the derived classes should be used.

I can see that Collider derives from Component, but my scripts must derive from MonoBehaviour. Does it mean I can not simulate this behavior? Any suggestions?

If the class is not supposed to be used as a component (or instantiated, for example with the ‘new’ keyword) at all, you can make the class abstract, which will prevent the script from being added. I am assuming you want to use inheritance, otherwise you can make it static.

If you do need to create instances of the class, I don’t think you can prevent it from being added, but you can throw an error into the console and then remove the component. You can use the OnValidate() function for that.

#if UNITY_EDITOR // Only runs in editor, doesn't get compiled on build
void OnValidate () {
    // Show an error in the console: (you can also do LogWarning or Log)
    Debug.LogError("This script should not be added as a component! Removing...");
    // Destroy the component (of course, replace "YourComponent" with the actual class)
    Destroy(GetComponent<YourComponent>());
}
#endif