Hi I am trying to instantiate some UI elements but I am stuck on the buttons, they all appear fine and they are generated with the script attached so no worries their but I can not figure out how to change the return value to the script I have attached.
Debug.Log("found:" + contact.GetComponentsInChildren<Button>().Length + " buttons");
Button[] button = contact.GetComponentsInChildren<Button>();
for (int i2 = 0; i2 <= contact.GetComponentsInChildren<Button>().Length; i2++)
{
//set button value to i
button[i2].
}
If you’re gonna modify that stuff it might be easier to add our own delegates to the button. I’m not sure you can modify an event that’s already in place, and I think this might be by design in order to keep one system from interfering with another. The whole point of events is to keep everything compartmentalized.
Here’s some more discussion on adding events:
Keep in mind your i2 variable needs to be captured (usually to another local int variable) or else all buttons will respond with the final value of i2 after the loop completes. Google for capturing variables, but it just means making an extra local copy within the loop and using that copy in your delegate.
but im banging my head against a wall trying to make these persistent and only created once
So far I’ve ended up with, which creates them with the correct values but on click it goes over the array limit and sticks at max+1. What id like to do is create them only once and have them be persistent.
for (int i = 0; i < player.gameObject.GetComponent<PlayerData>().contact.Length; i++)
{
Debug.Log("found:" + contact.GetComponentsInChildren<Button>().Length + " buttons. Setting target to " + i );
//contact.GetComponentInChildren<Button>().onClick.AddListener(delegate { player.GetComponent<PlayerPhone>().call(i); });
Button[] button = contact.GetComponentsInChildren<Button>();
//button[0].onClick.AddListener(delegate { player.GetComponent<PlayerPhone>().call(i); });
button[0].onClick.AddListener(() => player.GetComponent<PhoneContacts>().call(i));
Debug.Log("Set call to #" + i);
button[1].onClick.AddListener(() => player.GetComponent<PhoneContacts>().wayPoint(i));
Debug.Log("Set Waypint to #" + i);
GameObject targetInfo = UnityEvent.GetValidMethodInfo(player.GetComponent<PhoneContacts>().call(i) //am i getting close? ) ;
UnityAction methodDelegate = System.Delegate.CreateDelegate(typeof(UnityAction), button[0], targetInfo) as UnityAction;
//UnityEventTools.AddPersistentListener()
}
Every time you call .AddListener() you are adding again a fresh call to the delegate. That’s not what you want, unless in the intervening time you have called .RemoveListener() to remove it first.
Take a look at a few delegate tutorials, get a feel for what you’re working with.