Author Topic: UIEventListener - Dynamic function  (Read 2695 times)

thibaud

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
UIEventListener - Dynamic function
« 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.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UIEventListener - Dynamic function
« Reply #1 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.

thibaud

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
Re: UIEventListener - Dynamic function
« Reply #2 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); };

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UIEventListener - Dynamic function
« Reply #3 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.