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?
A delegate is sort of list. So you can just use.
Action myDelegates;
myDelegates += Use;
myDelegates += Destroy;
Button.onClick.AddListener(myDelegates);
Sorry understood the question wrong... Yeah it should work after fixing some syntax stuff, but why shouldn't it?
Answer by Fikule · Jan 08, 2017 at 07:07 PM
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! :) (Just need to clear the list afterwards ^^)
Your answer
Follow this Question
Related Questions
unity 2018.3.12f1 Button OnClick call function on another instance? of script 0 Answers
How can I make mobile UI buttons fire when first touched rather than released? 0 Answers
Can't disable TMPro Buttons 1 Answer
CrossPlatformInput Detect Multiple Input Headache 1 Answer
Is it possible to get the screen rect for a button regardless of its parent? 1 Answer