Home > Software design >  How to change list element from inspector?
How to change list element from inspector?

Time:11-23

I have a ScriptableObject which defines a quest in a game.
Quest contains List, QuestStep is an abstract class
KillStep and ReachDestinationStep inherited from QuestStep
I need a way to add steps in a list and select its type from inspector window.

I've already made UI for this behavior, it should look like this: enter image description here

1 - KillStep element in a list

2,3 - abstract QuestStep with dropdown & button to select step type and create it in place of selected element

I've got pretty close, but all i can do is to change the whole list and i can't find reference to list element or its index.
Tried objectReferenceValue but it gives an error: type is not a supported pptr value, and managedReferenceValue is null Code sample:
`

[CustomPropertyDrawer(typeof(QuestStep))]
public class QuestStepDrawer : PropertyDrawer
{
    private SerializedProperty currentProperty;
    enum QuestStepType
    {
        Kill,
        ReachDestination
    }
    private QuestStepType stepType = QuestStepType.Kill;
    

    public override VisualElement CreatePropertyGUI(SerializedProperty property)
    {
        currentProperty = property;
        var container = new VisualElement();
        container.Add(new EnumField("Step to create:", stepType));
        container.Add(new Button(InitStep));

        return container;
    }

    private void InitStep()
    {
        //here i want something like SetValue(currentProperty.objectReference = new KillStep());
        fieldInfo.SetValue(currentProperty.serializedObject.targetObject, new List<QuestStep>(){new KillStep()});
    }
}

`

CodePudding user response:

Oh, i completely forgot about ReorderableList.onAddDropdownCallback, just what i needed. Too bad it only works with IMGUI
Code sample:

list = new ReorderableList(serializedObject, 
            serializedObject.FindProperty("Steps"), 
            true, true, true, true);
list.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) => {
            var menu = new GenericMenu();
            menu.AddItem(new GUIContent("KillStep"), false, clickHandler, new KillStep());
            menu.AddItem(new GUIContent("ReachDestinationStep"), false, clickHandler, new ReachLocationStep());
            menu.ShowAsContext();
        };

UI

  • Related