Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializefield for UnityAction in inspector

I have a script with :

[SerializeField]
private List<UnityAction> m_method = new List<UnityAction>();
private List<Button> m_button = new List<Button>();

void Start()
{
    //init m_button 
}


// this function is called when the player click on an object in game
void onClick()
{
    for(int i=0; i<m_button.Count; i++)
        m_button[i].AddListener(m_method[i]);
}

I want to define the unityAction from inspector, but nothing appears in inspector... I thought it would be something like the button component : enter image description here

Is there a way of binding action to buttons with serialize field in inspector ?

like image 976
lufydad Avatar asked Oct 28 '25 18:10

lufydad


1 Answers

What you want is not UnityAction, isUnityEvent, this last one can be serialized on to the inspector.

Difference is well explained in UnityForums.

UnityAction is like:

 public delegate void UnityAction();

And UnityEvent is just another way to handle events with the (great) possibility to be serialized so as to be used in the Editor (Inspector) in contrary to plain C# events. A simple example is the onClick event of a Button.

If you want to pass UnityEvent to the AddListener method, you can use lambda expresions like this:

btn.onClick.AddListener(() => unityEvent?.Invoke());

Notice the "?" to avoi calling null (empty) actions!

like image 106
Lotan Avatar answered Oct 30 '25 12:10

Lotan