Adding a list of delegates to AddListener

Basically I know you can do the following:

obj.GetComponent<Button>().onClick.AddListener(delegate {Use;});

What I want to do is use an array of delegates to create multiple listeners on buttons.

something like this:

List myList<Delegates> = new List<Delegates>();

myList.add(Use);
myList.add(Destroy);
myList.add(Etc);

foreach(Delegate delegate in myList
{
            GameObject obj = (GameObject)Instantiate(MyButton, myTransform);
            obj.GetComponent<Button>().onClick.AddListener(delegate);
}

Is this possible? The end result is a UI with buttons for each method stored this way on an object. So different objects will have different methods stored and generate a different set of buttons for the UI. If it isn’t possible, what would be the best way to achieve this?

Got it working. My issue was simply that I wasn’t properly using UnityAction ><

Now I have (in UnableObject):

public List<UnityAction> buttonCommandList = new List<UnityAction>();

public virtual void CreateUIInterface(Text titleText, GameObject buttonMenu, GameObject toolTipButton, PlayerInteraction playerInteraction)
{
    Debug.Log("Creating Interface");
    titleText.text = GetName();
    foreach (UnityAction command in buttonCommandList)
    {
        GameObject obj = (GameObject)Instantiate(toolTipButton, buttonMenu.transform);
        obj.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
        obj.GetComponent<Button>().onClick.AddListener(command);
        Debug.Log("command: " + command);
        Debug.Log("obj: " + obj.name);
    }
}

And in my inheriting class:

public override void CreateUIInterface(Text titleText, GameObject buttonMenu, GameObject toolTipButton, PlayerInteraction playerInteraction)
{
    buttonCommandList.Add(delegate { this.Use(1); });
    buttonCommandList.Add(this.Destroy);
    buttonCommandList.Add(this.Switch);

    base.CreateUIInterface(titleText, buttonMenu, toolTipButton, playerInteraction);
}

All good! :slight_smile: (Just need to clear the list afterwards ^^)