How to make a callback for a DropdownField?

I have a DropdownField in my editor window and want to know when the value gets changed. I tried several things and searched for all kind of stuff but can’t get it to work.

I mainly tried it with the myDropdownField.RegisterCallback(func) way that is taught in the course.
I tried DropdownMenuEventInfo, KeyDownEvent and MouseUpEvent. The last two events only work if the mouse is over the label of the field which obviously isn’t helping.

So how can get the callback i need?

The way I do it is with the RegisterValueChanged() method.
Here’s an example from my InventoryItemEditor I’m working on:

                pickupDropDown = new DropdownField("Pickup", strings, index);
                pickupDropDown.RegisterValueChangedCallback(SetPickup);
        private void SetPickup(ChangeEvent<string> evt)
        {
            var property = serializedObject.FindProperty("pickup");
            List<Pickup> items = Statics.GetAssetsOfType<Pickup>();
            property.objectReferenceValue =items[pickupDropDown.index];
        }

The trickiest part of using RegisterValueChangedCallback is that the ChangeEvent<T> must be typed correctly. In other words, you need to know the exact type of callback that the Element requires.

You can choose to make a method to call with the correct signature, or you can use an anonymous method (sometimes called a closure).

Here’s an example:

myDropdownField.RegisterValueChangedCallback((evt)=>
{
    Debug.Log($"The value has changed to {evt.newValue}.");
}

The best part of this example is that the type for the ChangeEvent<T> is inferred by the compiler. You don’t need to put ChangeEvent evt, because the compiler is expecting a ChangeEvent<string>.

Remember that the new string value of the DropdownField will be stored in evt.newValue, but you can also access the DropdownField.index to get the index into the List you provided for the choices.

1 Like

Thank you for the quick help. I already tried your solution and it works perfect.

Have a nice day :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms