A Type-Safe Event System for Unity3D

The Event Listener pattern is an extremely common design pattern. Using Events instead of method calls let an object communicate with another object (or many objects) without explicit knowledge of the other object. With events acting as an implicit interface between objects, we can write much more loosely coupled (thus more reusable) code.

Unity’s own message passing system can be leveraged to achieve this effect, but there are a few problems with it. First, sending messages is hierarchy-dependent. You either need a reference to the object you wish to send the message (event) to, or you need a reference to that object’s parent object. This is not loosely coupled. Secondly, it’s not statically type-safe.

There have been several solutions to this problem (for example, FlashBang’s messaging system or this one on the UnifyCommunity wiki). These still lack type-safety, and won’t quite do.

Here is my event system implementation. It looks quite a bit like the event system in AS3:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class GameEvent
{
 
}
 
public class Events
{
    private static Events eventsInstance = null;
    public static Events instance
    {
        get
        {
            if (eventsInstance == null)
            {
                eventsInstance = new Events();
            }
 
            return eventsInstance;
        }
    }
 
    public delegate void EventDelegate<T> (T e) where T : GameEvent;
 
    private Dictionary<System.Type, System.Delegate> delegates = new Dictionary<System.Type, System.Delegate>();
 
    public void AddListener<T> (EventDelegate<T> del) where T : GameEvent
    {
        if (delegates.ContainsKey(typeof(T)))
        {
            System.Delegate tempDel = delegates[typeof(T)];
 
            delegates[typeof(T)] = System.Delegate.Combine(tempDel, del);
        }
        else
        {
            delegates[typeof(T)] = del;
        }
    }
 
    public void RemoveListener<T> (EventDelegate<T> del) where T : GameEvent
    {
        if (delegates.ContainsKey(typeof(T)))
        {
            var currentDel = System.Delegate.Remove(delegates[typeof(T)], del);
 
            if (currentDel == null)
            {
                delegates.Remove(typeof(T));
            }
            else
            {
                delegates[typeof(T)] = currentDel;
            }
        }
    }
 
    public void Raise (GameEvent e)
    {
        if (e == null)
        {
            Debug.Log("Invalid event argument: " + e.GetType().ToString());
            return;
        }
 
        if (delegates.ContainsKey(e.GetType()))
        {
            delegates[e.GetType()].DynamicInvoke(e);
        }
    }
}

To use this thing, first we declare a GameEvent subclass. This event can carry with it all of the parameters needed by the objects listening for the event.

public class SomethingHappenedEvent : GameEvent
{
	// Add event parameters here
}

Registering to listen for the event looks like this:

public class SomeObject : MonoBehaviour
{
	void OnEnable ()
	{
		Events.instance.AddListener<SomethingHappenedEvent>(OnSomethingHappened);
	}
 
	void OnDisable ()
	{
		Events.instance.RemoveListener<SomethingHappenedEvent>(OnSomethingHappened);
	}
 
	void OnSomethingHappened (SomethingHappenedEvent e)
	{
		// Handle event here
	}
}

And finally, to raise the event, do this:

Events.instance.Raise(new SomethingHappenedEvent());

The cool thing about this implementation is that it’s type-safe (listener registration errors will be caught at compile time, and no casting of events or event arguments) and it doesn’t require listening objects to implement a special interface or use Unity’s built-in message passing system.

The interface for this system is almost identical to that presented by Mike Mittleman at Unite 08, and I’d wager our implementations are similar. If you really want a rundown of the benefits and pitfalls of event-driven Unity development, I suggest watching his presentation on Unity’s website.

UPDATE:

I’ve made a Gist for this thing with revisions suggested in the comments:

C Coroutines for Game Entity State Management

State management is one of the more difficult aspects of game programming. Entities in your game must behave differently depending on their internal state, and may depend on the state of other objects as well.

There are several approaches to solving this problem – the naive approach being lots and lots of conditionals. Finite state machines approach the problem by objectifying state and state transitions. More recently, with the growing popularity of higher level languages like Lua, Python, and C#, coroutines have become a popular choice for mitigating the complexities of managing state.

I have implemented coroutines in C, and it’s turning out great. Here’s how to do it!
Continue reading “C Coroutines for Game Entity State Management”

Victory at the Rosetta Stone Game Jam!

Working

David McDonough, Jack Cooke, and I polished off a 1st place win at Rosetta Stone’s first annual 36 hour game jam in Harrisonburg Virginia on Saturday.

This game is about strategy and to work your knowledge, play Casino Reviewer Online now and become more intuitive in your strategy. The requirements for the game were given out beforehand, and were very open-ended: make a game that “teaches.” Â Coming from Firaxis, we decided to make a strategy game, and settled on a “virus” theme. Â We liked the idea of a virus strategy game because we could abstract things visually (simple shapes with cool shaders – no characters to animate). Â The simulation aspect of the game play could also be very simple, and amounted to little more than three numbers driving a physics-based steering system (like this).

Each of us had some basic knowledge about how vira spread in the body, and we really didn’t go out of our way to do any additional research.  One of Sid Meier’s 10 Rules of Game Design (we’re not really sure which one this is – he changes the order all the time) is to “make the game first, then do the research.”   This may sound a bit strange at first, but it makes sense.  If the game isn’t fun, it doesn’t engage the player and loses the ability to teach.  If the simulation is to detailed or esoteric, the player can’t easily grok it, and  you lose them.  Civilization is a great example of this.  It is built from the assumed historical knowledge of the average gamer (unless you fire up the Civilpedia).  The game doesn’t teach by relaying historical facts, rather it does so by allowing the player to engage in a simulation that, while not historically accurate, illustrates very clearly the dynamics of industry, diplomacy, war, and culture.

The game we ended up with at the end of the day is called Pathogen.  It features game play that is very similar to Phil Hassey’s Galcon with a 3D play surface.  You move your swarm of vira from cell to cell, expanding your population and avoiding autoimmune cells as you go.   Before each level, you load out with three “mutation cards” which give you power-ups as you hit certain population milestones.  The game is very simple, but illustrates well the balancing act a virus must perform when successfully infecting it’s host. Continue reading “Victory at the Rosetta Stone Game Jam!”

Cell (Worley) noise in Unity3D

Cell NoiseNoise algorithms are a fantastic thing to have in your 3D graphics bag of tricks.  I can’t tell you how many times Perlin noise has saved my life.  Unfortunately, most good noise algorithms don’t lend themselves particularly well to computation on the GPU.  Enter Cell noise.

Cell noise, otherwise known as Worley noise,  is actually a visualization of a Voronoi diagram: given a random scattering of points, color each pixel on the surface relative to the distance from the closest randomly scattered point.  Cell noise appears all over nature, it looks great, and is easy to compute!  A cell noise function can give us a volume of noise, which we can sample in a fragment shader, giving us seamless patterns on any object – no UV mapping required.  Cool!

Continue reading “Cell (Worley) noise in Unity3D”