Bindable Enumerations

As much as I love BindableValues, there are still some features that are frustratingly out of reach. First and foremost, I wish we lived in a world where enumerations in C# implemented IEquatable, so they could be made bindable. Despite throwing a couple of workarounds their way, nothing was ever good enough to stick, and my enumerated values continued to loll about, unbound. I couldn’t take it anymore! I settled on a solution that was disappointingly duplicative, but practical: clone the functionality of BindableValues to create a new wrapper specifically for enumerations.

// --------------------------------
// <copyright file="BindableEnum.cs" company="Rumor Games">
//     Copyright (C) Rumor Games, LLC.  All rights reserved.
// </copyright>
// --------------------------------

using System;
using System.Collections.Generic;

/// <summary>
/// BindableEnum class.
/// </summary>
/// <typeparam name="T">Backing value type.</typeparam>
public class BindableEnum<T> where T : struct, IComparable, IFormattable, IConvertible
{
    /// <summary>
    /// Backing value, serialize to show in Inspector.
    /// </summary>
    [UnityEngine.SerializeField]
    private T backingValue;

    /// <summary>
    /// Event raised when bindable value changes.
    /// </summary>
    public Action<T> OnValueChanged;

    /// <summary>
    /// Gets or sets the bindable value.
    /// </summary>
    public T Value
    {
        get
        {
            return this.backingValue;
        }
        set
        {
            if (!this.Equals(value))
            {
                this.backingValue = value;
                if (this.OnValueChanged != null)
                {
                    this.OnValueChanged(this.backingValue);
                }
            }
        }
    }

    /// <summary>
    /// Initializes a new instance of the BindableEnum class.
    /// </summary>
    /// <param name="value">Initial value.</param>
    public BindableEnum(T value)
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("Argument must be an enumerable type.");
        }

        this.backingValue = value;
    }

    /// <summary>
    /// Implicitly convert BindableEnum to backing value type.
    /// </summary>
    /// <param name="bindableEnum">BindableEnum to convert.</param>
    /// <returns>Backing value.</returns>
    public static implicit operator T(BindableEnum<T> bindableEnum)
    {
        return bindableEnum.Value;
    }

    /// <summary>
    /// Determines whether one BindableEnum is equal to another.
    /// </summary>
    /// <param name="a">First BindableEnum with value of type T to compare.</param>
    /// <param name="b">Second BindableEnum with value of type T to compare.</param>
    /// <returns>True if the BindableEnums are equal.</returns>
    public static bool operator ==(BindableEnum<T> a, BindableEnum<T> b)
    {
        if (ReferenceEquals(a, null))
        {
            return ReferenceEquals(b, null);
        }

        return a.Equals(b);
    }

    /// <summary>
    /// Determines whether one BindableEnum type is not equal to another.
    /// </summary>
    /// <param name="x">First BindableEnum with value of type T to compare.</param>
    /// <param name="y">Second BindableEnum with value of type T to compare.</param>
    /// <returns>True if the BindableEnums are not equal.</returns>
    public static bool operator !=(BindableEnum<T> x, BindableEnum<T> y)
    {
        return !(x == y);
    }

    /// <summary>
    /// Determines whether the specified object is equal to the current object.
    /// </summary>
    /// <returns>True if the specified object is equal to the current object; otherwise, false.</returns>
    /// <param name="obj">The object to compare with the current object.</param>
    public override bool Equals(object obj)
    {
        // is the object null?
        if (ReferenceEquals(obj, null))
        {
            return false;
        }

        // are they the same instance?
        if (ReferenceEquals(this, obj))
        {
            return true;
        }

        // are the values equal?
        if (obj is T)
        {
            return this.Equals((T)obj);
        }

        // are they the same type?
        if (obj.GetType() != this.GetType())
        {
            return false;
        }

        // are they otherwise equal?
        return this.Equals((BindableEnum<T>)obj);
    }

    /// <summary>
    /// Serves as a hash function for a particular type. 
    /// </summary>
    /// <returns>A hash code for the current object.</returns>
    public override int GetHashCode()
    {
        unchecked
        {
            return (EqualityComparer<T>.Default.GetHashCode(this.backingValue) * 397) ^ (this.OnValueChanged != null ? this.OnValueChanged.GetHashCode() : 0);
        }
    }

    /// <summary>
    /// Determines whether the specified object is equal to the current object.
    /// </summary>
    /// <returns>True if the specified object is equal to the current object; otherwise, false.</returns>
    /// <param name="other">The object to compare with the current object.</param>
    protected bool Equals(BindableEnum<T> other)
    {
        return this.Equals(other.backingValue) && Equals(this.OnValueChanged, other.OnValueChanged);
    }

    /// <summary>
    /// Determines whether the specified object is equal to the current object.
    /// </summary>
    /// <returns>True if the specified object is equal to the current object; otherwise, false.</returns>
    /// <param name="other">The object to compare with the current object.</param>
    protected bool Equals(T other)
    {
        return EqualityComparer<T>.Default.Equals(this.backingValue, other);
    }
}

And some basics on how to use it… Continue reading

Unnatural Disaster

Global Game Jam 2014. It’s late Saturday night, on the eve of our home stretch. My team was well ahead of schedule. We’d gone with an unusual project, a card game, so we’d been playtesting in no time, working well together all weekend and making great progress. Many hands make light work, and with ten people on our team, work was plenty light.

But with everything going so smoothly, it was almost as if I was missing out on the real jam experience. Looking around at the other teams struggling to finish, I almost felt… guilty. So, I decided to up the challenge for myself a bit. As the clock rolled over midnight – less than a day to go – I popped open Unity and started working on a second game, this time on my own.

I called the project Unnatural Disaster.

Continue reading

Event Aggregator

The next step up from simple events is the complete decoupling of the event publisher and event receiver through an event aggregator. Consider the case of a game over message. The game is decided to end by a rule manager class. Lots of things want to subscribe to this event: the game over UI, the input manager, any systems that spawn players or items or track score. But aside from the game over state, none of those systems have any reason to take a dependency on the rule manager. Instead, we’d like to abstract the publishing of events and receiving of them through an intermediary: the event aggregator.

I’ve seen several event dispatching solutions for sale on the Asset Store, but I decided to roll my own. I based my approach on the EventAggregator from Microsoft’s wonderful Prism library.

Continue reading

Liftoff

A while back I had an idea for a game about launching rockets. Way out of my comfort zone, right? Basically it would be a blend of the engineering and rocket building of Kerbal Space Program, but with a greater emphasis on moment-to-moment skill instead of meticulous planning. I took about a day to prototype the idea, and while I’m not sure if I’m going to do something with it in the future, I did find myself spending a lot more time playing with it than I did building it!

Hold mouse button down to thrust, release to separate stage. Hold down A or D to steer left or right. Reset with Esc.

While the implementation was extremely basic, it was effective at proving the idea and teaching me some interesting things that might be useful later.

Continue reading

The Evolution of Aiming in Voyager

Voyager is a game is about science. Not just in the “you’re launching a space probe” sense, but in that the core loop is about experimentation. Make a hypothesis (I need to launch at about 45°), perform the test (3, 2, 1… LIFTOFF), observe the result (missed wide right!), refine the hypothesis (let’s try 30° next time). It took a long time to figure out how to make this process feel natural and intuitive.

In order for it to work, the game needed three things:

  • Feedback: I need to be able to tell how my current aim differs from my last aim.
  • Determinability: If I do the same thing two different times, I should get the same result both times.
  • Precision: I should be able to execute the move as I intended. If I try to launch at an angle of 19°, I should not accidentally launch at 20° or 18° instead.

Solving feedback was the easiest part. The aiming mechanism is very explicit, with an arrow showing the direction and relative power the probe will launch in. Previous launches are shown as dimmer arrows, so the player can easily line up a similar shot and tell how their new one differs. It also straight up tells the user the angle and power of their shot in text, so the values can be written down and reused later. And finally, in-flight probes leave a trail of breadcrumbs, so it’s easy to tell when and how a trajectory diverges from an older one.

Aiming Launch

So much feedback

Continue reading

Dependency Provider

NOTE: I no longer use, or recommend, the DependencyProvider. There are a number of reasons why this is the case, not the least of which because it didn’t work on certain platforms. But by not using it, I found myself missing its ability to cache found references to speed up lookup time, and didn’t need the object instantiation and lifetime management stuff so much. So I kept what I liked, ditched what I didn’t, and ended up with the much simpler DependencyLocator I now use in lieu of FindObjectOfType.

// --------------------------------
// <copyright file="DependencyLocator.cs" company="Rumor Games">
//     Copyright (C) Rumor Games, LLC.  All rights reserved.
// </copyright>
// --------------------------------

using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// DependencyLocator class.
/// </summary>
public class DependencyLocator : MonoBehaviour
{
    /// <summary>
    /// Cached DependencyLocator instance.
    /// </summary>
    private static DependencyLocator dependencyLocator;

    /// <summary>
    /// Cache references to component instances.
    /// </summary>
    private readonly IDictionary<Type, Component> instances = new Dictionary<Type, Component>();

    /// <summary>
    /// Locate an instance of the given component type.
    /// </summary>
    /// <typeparam name="T">Type of component to locate.</typeparam>
    /// <returns>Instance of the desired component.</returns>
    public static T Find<T>() where T : Component
    {
        // check whether we have a dependency locator instance
        if (dependencyLocator == null)
        {
            // create a new game object and attach our component
            var gameObject = new GameObject(typeof(DependencyLocator).ToString());
            dependencyLocator = gameObject.AddComponent<DependencyLocator>(); 
        }

        // ask scene dependency locator for a scene instance
        return dependencyLocator.Get<T>();
    }

    /// <summary>
    /// Provide an instance of the given component type by retrieving it from the cache or finding one in the scene.
    /// </summary>
    /// <typeparam name="T">Type of component to provide.</typeparam>
    /// <returns>Instance of the desired component.</returns>
    public T Get<T>() where T : Component
    {
        var type = typeof(T);
        if (!this.instances.ContainsKey(type))
        {
            this.instances.Add(type, FindObjectOfType<T>());
        }

        return (T)this.instances[type];
    }
}

Original post:

Previously, I wrote about the process of locating dependencies in Unity. I enumerated some of the reasons the singleton pattern leads to bad practice, and how good process lead to better, more maintainable code.

And fine, I’ll admit it. I think singletons are ugly and I don’t like them:

TypicalSingleton.Instance.DoSomething(); // gross

Instead, I’d like to offer an alternative, one that doesn’t require a bunch of boilerplate code in every class I want to make globally and performantly accessible. Continue reading

Locating Dependencies

Most components don’t exist in isolation. Sooner or later, they’re going to need to talk to each other, which raises the question of how they should acquire references to one another. In Unity, this is easily accomplished in the editor: expose the type you’re looking for as a public field, then wire it up in the inspector by dragging an instance of the dependency onto the field. I actually really like this approach! It’s essentially a form of dependency injection. This works well for objects in a scene, or relationships between different scripts in a prefab, but it isn’t well suited for items instantiated at runtime. It’s also brittle, since changing the type expected or provided will break the association. These situations call for a different approach to locating dependencies.

Continue reading

Scene Name Attribute

Lots of times, I have scripts that need to be configured with the name of a specific scene. A button might need the name of the menu it loads when clicked, or a door trigger might need to know which level to transition to. Scenes are represented by strings, and therefore are easy to mistype in the Inspector. But in the editor, we have the luxury of a comprehensive list of the scenes in our build, something I leveraged before in my Scene Switch window. Let’s use that same idea to power an attribute (and attribute drawer) to provide a convenient and friendly way to enforce correct scene names every time.

Continue reading