How I can change listener via script?
I have a script what creates a buttons and add listener to every button. But if I make whats like this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Example : MonoBehaviour
{
public Button ExampleButton;
void Awake()
{
ExampleButton.onClick.AddListener(ExampleMethod(5));
}
void ExampleMethod(int a)
{
Debug.Log(a);
}
}
It`s doesn`t work... How I can dynamicaly change OnClick function on my button, and how I can call methods/functions with some parameters with this button?
Comment
Best Answer
Answer by ShadyProductions · Sep 05, 2020 at 11:43 AM
ExampleButton.onClick.AddListener(() => ExampleMethod(5));
or for adding/removing:
UnityAction UA;
UA = new UnityAction(() => ExampleMethod(5));
ExampleButton.onClick.AddListener(UA);
ExampleButton.onClick.RemoveListener(UA);