User Tools

Site Tools


Using .NET event delegates

While Unity's SendMessage() method to broadcast gesture event notifications is very convenient to use, it is not as efficient or flexible as regular .NET events. That's why FingerGestures 3.0 supports both approaches.

Gesture Events

Every GestureRecognizer exposes a public OnGesture .NET event that is fired every time the gesture/finger event is detected. The event signature is the same as its SendMessage equivalent. Here's a quick example of how to subscribe to the TapRecognizer's .NET event:

[RequireComponent( typeof( TapGesture ) )]
public class TapTutorial : MonoBehaviour
    void Start()
        // lookup our tap recognizer component on the same object
        TapRecognizer tap = GetComponent<TapRecognizer>();
        // subscripe to its .NET event
        tap.OnGesture += MyTapEventHandler;
    void MyTapEventHandler( TapGesture gesture )
        Debug.Log( "Tap detected at " + gesture.Position );

In some cases, you may also want to stop listening to a particular event. You can do that by unsubscribing your event handler from the gesture recognizer using the standard ”-=” syntactic sugar:

tap.OnGesture -= MyTapEventHandler;

Watch out for memory leaks when forgetting to unsubscribe from events belonging to objects whose lifetime you do not control. This is a pretty common pitfall of using .NET delegates.

Alternatively, the FingerGestures singleton also exposes a global OnGestureEvent hook that you can subscribe to in order to be notified whenever any active GestureRecognizer fires its gesture event:

void Start()
    FingerGestures.OnGestureEvent += FingerGestures_OnGestureEvent;
void FingerGestures_OnGestureEvent( Gesture gesture )
    Debug.Log( + " fired its gesture event" );
    if( gesture is TapGesture )
        Debug.Log( "Tapped: " + ((TapGesture)gesture).Taps );

Finger Events

FingerEventDetectors follow a similar pattern, although the event name is unique to each.

  • FingerUpDetector.OnFingerUp( FingerUpEvent e )
  • FingerDownDetector.OnFingerDown( FingerDownEvent e )
  • FingerHoverDetector.OnFingerHover( FingerHoverEvent e )
  • FingerMotionDetector.OnFingerMove( FingerMotionEvent e )
  • FingerMotionDetector.OnFingerStationary( FingerMotionEvent e )
  • FingerGestures.OnFingerEvent( FingerEvent e )
manual/advanced/event_delegates.txt · Last modified: 2013/03/12 13:39 by wravaine