Search Unity

Editor Script Dropdown that has ID and Value?

Discussion in 'Scripting' started by lofwyre, Aug 4, 2021.

  1. lofwyre

    lofwyre

    Joined:
    Apr 19, 2007
    Posts:
    174
    Hi

    From what I can see the EditorGUILayout.Popup returns just an index of the selected item. Is there another control that allows for a name/value binding in the list that will return the value rather than the index. Having the returned value dependent on the order of the list is problematic in a lot of ways, perhaps I'm missing something?

    All of the examples I've seen so far are very simple.

    Suppose I have

    QUEST
    ID = 10
    Name = This good Quest

    ID = 12
    Name = Another Quest

    I want to display them in the dropdown ordered by their "Name" but when selected I want to get the ID of the item. This seems harder to do than it should be.

    The code I'm using looks like this;
    Code (CSharp):
    1. for (int i = 0; i < ((DialogManager)target).Quests.Count; i++)
    2. {
    3.     int questCodeIndex = quests.FindIndex(q => q.QuestID == ((DialogManager)target).Quests[i].QuestID);
    4.     if (questCodeIndex == -1) { questCodeIndex = 0; }
    5.  
    6.     int newQuestID = EditorGUILayout.Popup("Quest", questCodeIndex, quests.Select(q => q.QuestName).ToArray());
    7.     ((DialogManager)target).Quests[i] = quests[newQuestID];
    8. }
    • The objects field being edited is a list of Quests
    • I'm iterating over each Quest to set which it is specifically within a list of avaialble quests
    • ((DialogManager)target).Quests is a reference to this objects list of quests
    • quests[] is the collection of available quests
    • I find the index in the collection using the QuestID
    • In the case that this is a new quest I default it to the first in the collection
    • Create the dropdown setting the selected to the located index
    • Save the objects field to what has been selected
    Produces this


    It works and doesn't present a performance issue, etc. It's just not as clean as I'd like.

    The collection is being loaded from a database in the OnEnable event.

    Any advice on this would be appreciated.

    Thanks
     
    Last edited: Aug 5, 2021
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    I wouldn't worry about performance of editor scripts unless you're doing something so computationally expensive you freeze the UI for a few seconds.

    You could cache your information into a dictionary with the name as the key and the id as the value, or create a small struct just to associate data in the editor.
     
  3. lofwyre

    lofwyre

    Joined:
    Apr 19, 2007
    Posts:
    174
    Yeah, thanks mate, it works. I'm just a little surprised I guess by how half done the UI system feels. There are probably reasons for it I'm not seeing so, it's cool. I've got it doing most of what I want now.

    Cheers