Is it possible to use || (or) with RequireComponent?

I made some scripts for my game objects that require a MeshCollider. [RequireComponent (typeof (MeshCollider))] is working fine. The thing is that some objects need different type of collider (box, sphere, etc) and therefore don’t need a MeshCollider.

So, can I use RequireComponent with || statement to use only the needed component. I was looking for something like this: [RequireComponent (typeof (MeshCollider)) || (typeof(BoxCollider))].

I feel that it is impossible considering that Unity creates the required component for us at object creation…

RequireComponent requires a Type argument, and || returns a boolean, so || is not appropriate here. However you can have up to three arguments separated with commas.

[RequireComponent( typeof(MeshCollider), typeof(BoxCollider) )]

If you need more than three, you can stack them up by having multiple RequireComponent directives above your class definition.

I’d avoid doing this too much though; it can get pretty annoying when you need to remove components. I usually just log a warning in the Awake function if the component isn’t there.

Hey there,

As people were saying you can write your own Inspector or even better an Attribute but that requires a bit of setup. What you could do is just use the Reset function that is in Unity on every MonoBehaviour.

  //Since we use editor calls we omit this function on build time
  public void Reset()
    AudioSource source = GetComponent<AudioSource>();
    Light light = GetComponent<Light>();

    if( source == null && light == null )
      if( UnityEditor.EditorUtility.DisplayDialog( "Choose a Component", "You are missing one of the required componets. Please choose one to add", "AudioSource", "Light" ) )

Reset gets called when add a component so this would do what you want it to. Here is what it looks like when you are missing the component.


Not possible out of the hat, no.

You could write an editor script for it, though. As soon as the script is instantiated in the hierarchy, it could open a popup asking you which of 2 components you want.

Excellent tutorial on editor scripts here.

The correct solution here is to require the parent class for the objects that you need.
For your example you’d need to require a Collider component, which is the base class for both BoxCollider and MeshCollider.

No you can not add multiple RequieComponent with OR notation