31 January 2016

Forwarding trigger events

Sometimes when developing any kind of game you want to have a function called on an object A (not necessarily a GameObject) when object B hits a trigger defined by object C. For example, A can be your game controller, B your player's avatar and C a trigger next to a door. When the avatar walks into the trigger you want to call something like

GameController.Instance.LoadLevel("nameofthelevel");

So you write a "DoorTrigger" monobehaviour with a public string member for the name of the level that should be loaded when the avatar walks into the trigger. Perfect.

The things is that this is a very common behaviour; often you just want to call one simple function on another object when the player (or something else) runs into a trigger and often the trigger object and the callee for the function is not the same object. Writing a new class for every occasion is cumbersome.

In the UnityEngine.UI namespace we have the EventTrigger class that solves exactly this issue, but then for input events. When a ui button is clicked the code for doing something with that event is often not in a monobehaviour on that button, but likely in some PanelController class that controls the panel. So you use the button's functionality to forward the event to that controller. The EventTrigger class does the same thing for other ui objects than buttons.

So we thought to take a peek at the open source implementation of EventTrigger and see if we could mimic the same easy editor interaction for physics trigger events. We finally came up with a class called ForwardTrigger that can be found here. It is very similar to the code of EventTrigger but a lot less complicated, since we don't have to deal with InputModules but simple trigger events.

We introduced a PhysicsTriggerEventData class that tells you what object the trigger was and what object the collider was. We also copied with very little changes the code of the editor for that class so that we can now forward physics trigger events as easily as we could forward click events:

A working example is hosted on this bitbucket repository called "UnityToolset". This repository will become the place where I'll add all code that I frequently use in multiple Unity projects (as long as it is not under NDA) and also all code that I write about on my blog. I welcome all feedback on this project!

No comments: