Author Topic: Anonymous Delegate with onFinished  (Read 2061 times)

flavoredCoffee

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 1
  • Posts: 15
    • View Profile
    • CWGTech Unity & Programming blog
Anonymous Delegate with onFinished
« on: January 06, 2014, 04:24:35 PM »
So, I want to set the alpha on all the child widgets of a given panel, and when the alpha reaches zero, then deactivate each widget.  I'm using the following code:

  1.                 UIWidget[] widgets = panel.GetComponentsInChildren<UIWidget>();
  2.  
  3.                 Debug.Log("found " + widgets.Length + " widgets!");
  4.  
  5.                 foreach (UIWidget w in widgets)
  6.                 {
  7.                         Debug.Log("Setting alpha tween on " + w.name);
  8.                         TweenAlpha.Begin(w.gameObject,duration,0.0f).onFinished.Add(new EventDelegate(delegate(){
  9.                                 Debug.Log("want to disable: " + w.name);
  10.                                 NGUITools.SetActive(w.gameObject,false);
  11.                         }));
  12.                 }

The Debug.Logs will illustrate the problem.  When I'm iterating over the list, w is set to each object and the 'setting alpha' debug log displays the correct object, however once the alpha fades out, the 'disable' debug log always shows the last item in the list for each alpha.onFinished.

So, either I need some way to have the w value used in the delegate to reference the value in the loop when it's created, or is there someway inside the delegate to get the object it's being run on?

flavoredCoffee

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 1
  • Posts: 15
    • View Profile
    • CWGTech Unity & Programming blog
Re: Anonymous Delegate with onFinished
« Reply #1 on: January 06, 2014, 04:34:31 PM »
A little digging into UITweener solved my problem.  Turns out just before calling the onFinished handler, the static variable UITweener.current is set to the object being worked on, so my code becomes:

  1.                         TweenAlpha.Begin(w.gameObject,duration,0.0f).onFinished.Add(new EventDelegate(delegate(){
  2.                                 Debug.Log("want to disable: " + UITweener.current.name);
  3.                                 NGUITools.SetActive(UITweener.current.gameObject,false);
  4.                         }));
  5.  

Which works as expected.