Search Unity

ObjectField that can take 2 types of objects

Discussion in 'Scripting' started by arvzg, May 17, 2019.

  1. arvzg

    arvzg

    Joined:
    Jun 28, 2009
    Posts:
    569
    Is there a way to make an ObjectField that can take 2 or more types of objects?

    For example, I want to make an ObjectField where you can assign only BoxCollider OR a SpriteRenderer, but no other types.

    My idea would be to make the ObjectField itself take any objects of type Object, then in OnInspectorGUI() I check the type of Object, if it doesn't match a type that I want, then... do/dont do something? The problem with that is it the slot itself will appear to accept any type, (you won't get that 'not allowed' icon when trying to assign the slot - it'll look like you can do it, but it just won't work)
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    3,614
    There is a simpler solution for this. The MonoBehaviours have an OnValidate method which runs when someone change something in the inspector and it does not run in run time. So you can validate whatever is in your exposed variables. The upside: it's simple and very quick to do, the downside is you have limited error message and it's not really fancy like a custom inspector.
     
    xVergilx likes this.
  3. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    1,658
    Alternatively - custom PropertyDrawer + Attribute that will do the same.