Tasharen Entertainment Forum

Support => NGUI 3 Support => Topic started by: thibaud on August 12, 2014, 01:20:36 AM

Title: UIEventListener - Dynamic function
Post by: thibaud on August 12, 2014, 01:20:36 AM
Hi

I know how to add an event to a button and it's work :

  1. go = Instantiate (prefabBtn, Vector3(0, 0, 0), Quaternion.identity);
  2. UIEventListener.Get(go).onClick = function(){ Debug.Log('click'); };
  3.  

But I need to create buttons in a loop and add parameter to my function

  1. for(var i = 0; i < 10; i++){
  2. go = Instantiate (prefabBtn, Vector3(i*100, 0, 0), Quaternion.identity);
  3. UIEventListener.Get(go).onClick = function(){ Debug.Log('click '+i); };
  4. }
  5.  

But with this code, all buttons display "Click 10" and not "Click 1" for the first, "Click 2" for the second.
I think I have scope issue but I don't find a workaround.


Thanks for your help.
Title: Re: UIEventListener - Dynamic function
Post by: ArenMook on August 12, 2014, 06:59:11 AM
1. Never use Instantiate. Use NGUITools.AddChild instead. You are creating elements in the middle of nowhere with Instantiate.

2. You need to pass your 'i' as a function parameter argument, and use UIButton.onClick instead.
Title: Re: UIEventListener - Dynamic function
Post by: thibaud on August 12, 2014, 07:56:46 AM
Ok for 1.

For 2., I try that without success :

  1. UIEventListener.Get(go).onClick = function(i : int){ Debug.Log('click '+i); };
Title: Re: UIEventListener - Dynamic function
Post by: ArenMook on August 13, 2014, 06:37:00 AM
UIEventListener functions expect the first parameter to be the game object. Check the class definition. UIEventListener is very limiting in this regard. This is why I suggested you to use the UIButton's onClick delegate instead.