Saturday, March 22, 2014

Hacking shoes for kids education (almost) – part 2: events in Unity3D

This is the second part of my report about the Code4Play hackathon. You can read part 1 here.

Let's dig into some technical details!

The FootMoov SDK includes a demo Unity project, that displays the current sensor values. The main Controller class exposes raw sensor data expressed as integer values.

To ease the job of the team on the game side, I wanted to wrap the given API with an event dispatcher. You can make components talk in different ways in Unity, but events represent the most efficient pattern for this purpose.

I never used events in C# before, but I was able to make a working abstraction layer in a reasonable time.

The behaviour is pretty simple: I publish a tap event when the pressure sensor passes a threshold value with a certain velocity.

Here are the distilled instructions of what you need to create an event dispatcher in Unity3D and, more in general, in C#.

The basic components are:
  • event delegates
  • events
  • listeners

First of all, you must define the delegate. It's a special C# type which is a sort of function wrapper. You can use the wrapped function as a callback.
public delegate void OnFrontTapEvent(object sender);
Then you create the event object, which is also part of C# syntax. When you define this object, you use the event keyword and the above-mentioned delegate as its type.
private event OnFrontTapEvent OnFrontTap;
The event acts as a container. You can add listeners to it with the += symbol.
OnFrontTap += new OnFrontTapEvent (listener.OnFrontTap);
The event is triggered by calling it like a method. This causes all the attached listeners to be called.
OnFrontTap (this);
You can find the complete code in the GitHub repo of the game projects. In particular, FootMoovAdapter is the class which uses the event system.

Be careful with scopes and locations where these components are initialised!


No comments:

Post a Comment