Search Unity

Question Override ObjectField Selection Menu

Discussion in 'Editor & General Support' started by Nexer8, Dec 5, 2021.

  1. Nexer8

    Nexer8

    Joined:
    Dec 10, 2017
    Posts:
    271
    I have an ObjectField where I would like to filter out specific objects that for different reasons should not be selected by the field. These objects can not be excluded by type, so I would need some way to set the criteria for what can show up in the object field selection menu myself. Is there any way to override the objects in the ObjectField selection menu?
     
  2. MvNimwegen

    MvNimwegen

    Joined:
    Dec 19, 2019
    Posts:
    56
    Unfortunately no. However, you could simply check whether the "new" value in the field is on of the accepted types. If not, simply do not accept the new value.
     
    Nexer8 likes this.
  3. Nexer8

    Nexer8

    Joined:
    Dec 10, 2017
    Posts:
    271
    Yeah, ended up doing something along those lines. Just feels a little weird from the user's experience. "Why would an object you are not allowed to select show up in the menu?"
     
  4. MvNimwegen

    MvNimwegen

    Joined:
    Dec 19, 2019
    Posts:
    56
    Well my main question would be, how would you see this being implemented? That line of code needs to return a value of a specific type. You say that the options cannot be excluded by type. How would you know which type to return or expect? If it could be anything, it would need to be returned as Component or Object. Both of which will need to be cast through some kind of switch statement anyway. And if you need to do that, you can simply use the current implementation.
     
  5. Nexer8

    Nexer8

    Joined:
    Dec 10, 2017
    Posts:
    271
    It is still type restricted, just with additional filters. Something like "Give me all instances of this type where the instance is not equal to X, or where the instance meets certain criteria". Basically, attach a function that takes in an item that will be shown in the menu, and returns whether it should be shown or not.

    In my particular case, I was searching for all instances of "graph", but did not want to show the "graph" that the object field was part of. The ability to attach a validation check to the menu would therefore be useful. Kind of like System.Linq where you can do
    Code (CSharp):
    1. List<int> numbers = new List<int>(){ 1, 2, 3, 4, 5, 6 };
    2. List<int> even = numbers.Where(n => n % 2 == 0).ToList();
    3. //2,4,6
     
  6. MvNimwegen

    MvNimwegen

    Joined:
    Dec 19, 2019
    Posts:
    56