Author Topic: UIToggle handler must be a member of a behaviour type  (Read 3276 times)

juharkonen

  • Guest
UIToggle handler must be a member of a behaviour type
« on: October 22, 2013, 07:47:52 AM »
As I didn't find related posts using the search feature, I wanted to drop a note here for future reference should someone run into the same issue (that is, I'm not requesting help but rather just pointing out an undocumented implicit constraint with the current EventDelegate implementation).

My UIToggle handler delegates weren't getting invoked when I switched toggle button states. I used a utility method like this that hid the static UIToggle.current.value from the handler:
  1. public static void SubscribeToggle(UIToggle toggle, Notification<bool> handler)
  2. {
  3.         EventDelegate.Add(toggle.onChange, delegate
  4.         {
  5.                 handler.Invoke(UIToggle.current.value);
  6.         });
  7. }
  8.  
where Notification<bool> inputs a bool and returns void.

The code above creates an anonymous delegate to be subscribed for onChange. However EventDelegate.Set initializes the handler target as
  1. mTarget = call.Target as MonoBehaviour;
  2.  
As the handler is an anonymous delegate and not a member of a derived MonoBehaviour, mTarget gets a null value. This causes the EventDelegate.isValid property to return false, and the handler won't be invoked.

I wonder if this is a necessary limitation; the only place where mTarget appears to be used as MonoBehaviour is in the EventDelegate.isEnabled property. This, however, is not used by NGUI.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UIToggle handler must be a member of a behaviour type
« Reply #1 on: October 22, 2013, 07:53:00 PM »
Yes, this has been reported before. You can't use anonymous delegates right now.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UIToggle handler must be a member of a behaviour type
« Reply #2 on: October 25, 2013, 12:56:28 AM »
Update: the latest 3.0.3 allows you to use anonymous delegates:
  1. EventDelegate.Add(btn.onClick, delegate() { Debug.Log("Click!"); });