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.