Custom drawer in unity3d to pick an enum – event tutorial followup

  • Part 1: basics event system
  • Part 2: event picker drawer for in-editor usage [you are here]
  • Part 3: debugging with platform dependant compilation
  • Part 4: multiple dispatchers
  • Part 5: optimization

For today’s tutorial we’re going to make something that’s really comfortable to use: a dropdown menu to select an event. We’ll do that by creating anEventPickerclass and a custom drawer by estending thePropertyDrawerclass thatUnityEnginekindly gives us.

First, well’need aEventPickerclass. This class will actually hold the data inside the game, and will not in any way define the editor UI. It’s the data for which we’re going to define a Custom Drawer in Unity3d, not the drawer itself.

custom drawer in unity3d
let’s make a custom drawer

The EventPicker class

To function with the Event system we defined in last tutorial we’ll need for it the ability to read which event channel and which specific event have been selected. It also needs to allow us to identify the specific type of enum to which each channel will be associated with, so that later the custom drawer can use this information to draw the appropriate dropdown menu. Therefore we’ll need at least :

  • one field to store the selected channel
  • one field to store the selected event for each channel
  • one property to give access to the actual currently selected event to any class that will actually use the event picker.
using UnityEngine;

[System.Serializable]
public class EventPicker
{
    public const string channelVarName = "channel";
    public eventChannels channel;

    public inGameChannelEvents inGame;
    public menuChannelEvents menu;

    public System.Enum Selected
    {
        get
        {
            switch (channel)
            {
                case eventChannels.menu: return menu;
                case eventChannels.inGame: return inGame;
                default:
                    Debug.LogError("EventPicker was passed an unimplemented channel!!! " + channel.ToString());
                    break;
            }
            return channel;
        }
    }


}

Sadly, this means that each time a channel is added inChannelEnumsclass, it will need to be added here too. Also, since we’re going to need a Drawer, we don’t have the freedom to choose whatever variable names we want to pick since it relies on getting that name as a string.

String-run-fools
A string! Run, you fools!

We could solve this problem with C# reflection but that’s a deep topic that I’d rather address another time. For now, let’s just use a strong naming convention and have the the event-storage variables use the same name as the channel, while we addchannelVarNameto keep thechannelvariable name as a constant string field near the variable whose name it stores, so that whenever we may need to rename it we can just as easily copy-paste that name inside the string.

TheSelectedproperty is just a switch that returns the value of the field described by the content of thechannelvariable. So that we have a fast way to get the selected event from theEventPicker.

The actual Custom Drawer

The Custom Drawer must have this declaration:

[CustomPropertyDrawer(typeof(EventPicker))]
public class EventPickerDrawer : PropertyDrawer
{

So that unity can assign this drawer to the class that it’s intended to draw. It’s also important to understand that we won’t be writing something from scratch here. We’ll actually be extending aPropertyDrawerclass that already exists in unity. I won’t explain in depth what this class is or does, for that there is the documentation, but please notice we’re going to override two methods:OnGUIandGetPropertyHeight.

Let’s begin with the easy part:

public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return base.GetPropertyHeight(property, label) * 3f + 5f;
    }

Now, what we’re doing here is basically telling unity to reserve a height equal to three times a normal variable plus an extra 5 pixels. This is because we’re going to put one header and then two dropdowns, and each one is going to use the height of one variable.

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PrefixLabel(position, label);
        Rect tempPos = position;
        tempPos.height = ROWHEIGHT;
        tempPos.y += ROWHEIGHT;
        tempPos.x += position.width * .4f;
        tempPos.width *= .6f;

TheOnGUIfunction actually tells unity what to draw in the inspector when it encounters anEventPickervariable. Here we start by telling it to draw a label which indicates the kind of objetc to which the data belongs and then declaring aRectwith the appropriate size and coordinates to store the rest of the UI elements.

        SerializedProperty channel = property.FindPropertyRelative(EventPicker.channelVarName);
        EditorGUI.PropertyField(tempPos, channel, GUIContent.none);

This bit of code recovers the data about thechannelvariable in theEventPickervia the serialization information (which means you can’t use this on anything that can’t be serialized), then draws new field with that information. Thechannelvariable is identified by its name, that we recover with the static string insideEventPicker.

        tempPos.y += ROWHEIGHT;
        eventChannels chosen = (eventChannels)channel.enumValueIndex;
        SerializedProperty selection = property.FindPropertyRelative(chosen.ToString());
        EditorGUI.PropertyField(tempPos, selection, GUIContent.none);

Here we increment the starting point of theRectso that Unity won’t draw the fields one over the other.

Then we proceed to get the value of the selected channel converted in itsenumform, so that we can then recover the serialization information for the appropriate variable by using theToStringmethod and benefitting from the strong naming convention used in theEventPickerclass.

That’s all folks

So, let’s recap: first you need to create the data container, but in a way that allows you to access all the names of the fields, then we can write another class that must be linked through aCustomPropertyDrawertag to the data class and that overrides thePropertyDrawerfunctions to draw our class the way we want it to.

Now you have a nice UI element that you can use to pick events for your Event System, without having to write it as a horrible string and then converting it. As usual down here there’s all the code in a copy-paste-friendly format. More on this event system is still coming next week. If you want to be sure not losing it, subscribe to my newsletter. For any feedback comments are below or you can just add me on twitter.

using UnityEngine;

[System.Serializable]
public class EventPicker
{
    public const string channelVarName = "channel";
    public eventChannels channel;

    public inGameChannelEvents inGame;
    public menuChannelEvents menu;

    public System.Enum Selected
    {
        get
        {
            switch (channel)
            {
                case eventChannels.menu: return menu;
                case eventChannels.inGame: return inGame;
                default:
                    Debug.LogError("EventPicker was passed an unimplemented channel!!! " + channel.ToString());
                    break;
            }
            return channel;
        }
    }
}

 

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(EventPicker))]
public class EventPickerDrawer : PropertyDrawer
{
    protected virtual float ROWHEIGHT
    {
        get
        { return 18f; }
    }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.PrefixLabel(position, label);
        Rect tempPos = position;
        tempPos.height = ROWHEIGHT;
        tempPos.y += ROWHEIGHT;
        tempPos.x += position.width * .4f;
        tempPos.width *= .6f;

        SerializedProperty channel = property.FindPropertyRelative(EventPicker.channelVarName);
        EditorGUI.PropertyField(tempPos, channel, GUIContent.none);
        tempPos.y += ROWHEIGHT;

        eventChannels chosen = (eventChannels)channel.enumValueIndex;
        SerializedProperty selection = property.FindPropertyRelative(chosen.ToString());
        EditorGUI.PropertyField(tempPos, selection, GUIContent.none);

    }
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return base.GetPropertyHeight(property, label) * 3f + 5f;
    }
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Event system: tutorial for Unity3D & C#

  • Part 1: basics event system [you are here]
  • Part 2: event picker drawer for in-editor usage
  • Part 3: debugging with platform dependant compilation
  • Part 4: multiple dispatchers
  • Part 5: optimization

Today I’ll start presenting you the single most useful piece of code that I’ve ever written. Since writing it I used it in every single project I’ve made, however simple. Even in game jams.
I’m speaking of an Event System. A class with no other purpose than to let other objects communicate with each other, with as little overhead as possible. And it’s implemented with delegates.

And it’s way better than SendMessage, if you ask me.

event_driven_programming

What’s an Event System?

Those of you who already know, just skip this paragraph. Still with me? good. The main problem you’ll have with SendMessage is that it needs to use a method’s name as an input. So the object sending the message not only needs to know what method should be invoked by the receiver, but also his name. In a case sensitive way. Want to change that name? too bad, the IDE won’t change the string for you. You’ll have to remember every single one of those and do it by yourself… or never change a function name ever again. Or remove one.

Sounds bad? it is. It’s a maintenance nightmare. Plus, it uses strings. Fuck strings. Strings are evil. They use your memory, trigger your garbage collector and spit on your mother. Never use them unless at gunpoint… and even then think twice about it and instead use an enum.ToString() if you can.

So what’s the solution? we need something more like this: you need to send a message between objects (or scripts) when a “thing” happens. So the scripts in the other object react to the “thing”. The caller script doesn’t need to know who or how will do anything in reaction to the “thing”. It just needs to shout out “Hey! I have a thing here!” and eventually how big the “thing” is. For instance, “Hey! I have a 3.5 Damage here!”. Then the health script subtracts the damage and the particle script spills blood everywhere. But the collider doesn’t need to know that. The “thing” is an Event. Shouting is a Broadcast. The reactions are called Callbacks or Handlers.

But this is nothing I invented, you can just study it here or here, or even here.

What’s a Delegate?

As before, if you know already, just skip ahead. Delegates are something I wish they did teach me in university, because they are just awesome. To put it bluntly: in C# you can treat functions as if they were variables and pass them as an argument to other functions. This means that you can change behaviours of an object at runtime. Or have an object hold and call a function without it even knowing what it does. Absolute decoupling. A maintenance heaven.

Before you can use a delegate, you first need to declare its type. Which means telling the compiler which return type and what arguments will be assigned to it. Not its name. Not its content. Just the signature structure. Of course, if you use as a signature something like:

public delegate object nameFunct(object o);

you can then pass anything and get anything (but say goodbye to compiler type-checks).

After you have declared a delegate type, you can then declare a delegate variable and assign to it a function with a matching signature. Just like you would do with any other variable. If you still need to delve deeper you can go here or here.

Get on with it!

gowi-2

Now, if you have seen my portfolio the event system there can be quite intimidating, but don’t worry, we won’t be doing that version right now. We’ll start with version 0.0.3 while that one is 1.0.1 [edit: this was before optimizing for the last part of the tutorial]. That makes about 100 rows of code and 20 headaches of difference.

Before we get to the main class, the event dispatcher, let’s define some stuff we’ll use there.

public delegate void gameEventHandler(eventArgExtend e);

This will be our event signature. Nothing to return because we don’t want the event sender to have anything to do with the receivers. The event type is this thing here:

public class eventArgExtend : System.EventArgs { }

Why didn’t I use directlySystem.EventArgs? Because in the future I may want to add something between those parentheses and when it happens it will cost me nothing to do so. Had I used directly that type it could require more work to do it.

Now, let’s get to something more interesting: defining the events themselves. To do so I’ll use something infinitely superior to strings: enums.

public enum eventChannels
{
    inGame
}
public enum inGameChannelEvents
{
    thing
}

Now we’ll need a comfortable way to pass this information to the dispatcher. For this I just created a class with a static function:

public class ChannelEnums
{
    public static Dictionary<eventChannels, System.Array> getChannelEnumList()
    {

        Dictionary<eventChannels, System.Array> enumChannelEventList = new Dictionary<eventChannels, System.Array>();
        enumChannelEventList.Add(eventChannels.inGame, System.Enum.GetValues(typeof(inGameChannelEvents)));
        return enumChannelEventList;
    }
}

Notice: adding a channel requires to add a new enum type, and there is no automated way to set a link between an enum value ineventChannelsand an other enumtype. So for each channel you need to add, you’ll have to write a new row of code like the one just before thereturn.

What we did here is to create a static function for the dispatcher. The function will recovery every event channel and every corresponding array of values, so that we can initialize the list of listeners in the dispatcher. All in the nice form of a Dictionary.

Now let’s get to the Event System

Our event system needs to be usable at EVERY stage of game play. This includes the Awake function of the first objects to be present in the first scene. Which means that I can’t use the Awake function to initialize the event system, or I would get in a race condition. That’s fucked up. But years of Unity3D ninjutsu allowed me to discover a precious thing: default values are initialized before Awake, and you can get them with static functions.

public class eventHandlerManager : MonoBehaviour
{
    static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> ListenerFunctions = initializeDicts();

What’s thatinitializeDicts? we’ll see later. For now just look at the type of ListenerFunctions: it’s a dictionary of dictionaries. It allows us to index gameEventHandler delegates first by channel and then by event.

Now we can write the key functions of the dispatcher: one to raise an event, one to add a delegate as listener, one to remove it.

public static void Broadcast( eventChannels evType,Enum ev,eventArgExtend e) 
	{
		ListenerFunctions[evType][ev](e);
	}
	
	public static void AddListener(eventChannels evType,Enum ev, gameEventHandler eventListener)
	{
		ListenerFunctions[evType][ev]+=eventListener;
	}
	public static void RemoveListener(eventChannels evType,Enum ev, gameEventHandler eventListener)
	{
		ListenerFunctions[evType][ev]-=eventListener;
	}

Why are they all static? because that way you don’t need to get the other classes to find the instance. Yes, this is limiting: you can’t have a damage event that only gets notified to one character. But for something more selective we’ll need to make a lot of changes, for the time being just add an identifier as field in the argument. Then have the receivers check that value. We’ll get back to that in future tutorials.

This is all that’s needed on the outside to use this event handler. Other classes that want to react to an event just need to declare a function that matches thegameEventHandlersignature and then invoke theaddListenerfunction giving that function as the last argument (without parentheses), and do the same for removal like this:

eventHandlerManager.AddListener(eventChannels.inGame, inGameChannelEvents.thing, onThing);

The broadcast use is even simpler:

eventHandlerManager.Broadcast(eventChannels.inGame, inGameChannelEvents.thing, new eventArgExtend());

So, now we’re almost done. There is just one last detail for the magic to fully work: how do we initialize and cleanListenerFunctions?

    public void OnDestroy()
    {
        ListenerFunctions = initializeDicts();
    }

    static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> initializeDicts()
    {
        Dictionary<eventChannels, Array> enumChannelEventList = ChannelEnums.getChannelEnumList();
        Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> result = new Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>>();
        foreach (var val in (eventChannels[])Enum.GetValues(typeof(eventChannels)))
        {
            result.Add(val, new Dictionary<Enum, gameEventHandler>());
            foreach (var ev in enumChannelEventList[val])
            {
                result[val].Add((Enum)ev, new gameEventHandler(delegate (eventArgExtend e) { }));
            }
        }
        return result;
    }

Wait a minute: did I initialize ListenerFunctions on destroy? Yes, because that is a static field. It will survive to the existence of the eventHandlerManager instance. And since that should only happen on a scene load, I can be sure that nothing should stay in the dictionary and that the new scene has a ready new clean slate to work on when the first Awake is called.

The initialization works by first getting the enum data from the static function we defined before in ChannelEnums, then using that data to initialize every field of the dictionary with an empitygameEventHandler; this way we can later add the Handlers with a+=instead of checking for a null field every time.

That’s all folks!

Not really. Actually there is a lot more that we can add to this class, mainly for debugging purposes, plus the “local” version of the event dispatcher that I mentioned before. But this tutorial is already huge, so maybe it’s better to deal with that stuff next week. If you want to be sure not losing it, subscribe to my newsletter. For any feedback comments are below or you can just add me on twitter.

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

public class eventHandlerManager : MonoBehaviour
{
    public static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> ListenerFunctions = initializeDicts();

    public static void Broadcast(eventChannels evType, Enum ev, eventArgExtend e)
    {
        ListenerFunctions[evType][ev](e);
    }

    public static void AddListener(eventChannels evType, Enum ev, gameEventHandler eventListener)
    {
        ListenerFunctions[evType][ev] += eventListener;
    }
    public static void RemoveListener(eventChannels evType, Enum ev, gameEventHandler eventListener)
    {
        ListenerFunctions[evType][ev] -= eventListener;
    }

    public void OnDestroy()
    {
        ListenerFunctions = initializeDicts();
    }

    static Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> initializeDicts()
    {
        Dictionary<eventChannels, Array> enumChannelEventList = ChannelEnums.getChannelEnumList();
        Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>> result = new Dictionary<eventChannels, Dictionary<Enum, gameEventHandler>>();
        foreach (var val in (eventChannels[])Enum.GetValues(typeof(eventChannels)))
        {
            result.Add(val, new Dictionary<Enum, gameEventHandler>());
            foreach (var ev in enumChannelEventList[val])
            {
                result[val].Add((Enum)ev, new gameEventHandler(delegate (eventArgExtend e) { }));
            }
        }
        return result;
    }
}

public enum eventChannels
{
    inGame
}

public enum inGameChannelEvents
{
    thing
}

public class eventArgExtend : System.EventArgs { }

public delegate void gameEventHandler(eventArgExtend e);

public class ChannelEnums
{
    public static Dictionary<eventChannels, System.Array> getChannelEnumList()
    {

        Dictionary<eventChannels, System.Array> enumChannelEventList = new Dictionary<eventChannels, System.Array>();
        enumChannelEventList.Add(eventChannels.inGame, System.Enum.GetValues(typeof(inGameChannelEvents)));
        return enumChannelEventList;
    }
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Scroll to select: image gallery tutorial

 

 

Every now and then in a UI you need the user to select an option among many, there are several ways to do so, one method could be the good’ole command line, another could be the use of toggles in a group (or radio button in Android/HTML environment), but that’s not nearly as cool as just looking at the thing you want and it being already selected. So today we’ll implement a scroll to select UI interface in unity3d.

We’ll do this in the image gallery that we’ve been building here for quite a while, here I’ll also give a unified version of the code with all of the features in it.

The idea is to define an area where the selection happens, so that whatever image happens to be in the area gets selected automatically. Of course the snapping behaviour works well with this but it’s not essential, since we are defining an area, not a single position.

Scroll to select area: let’s build it

It will go something like this:

select a ninja by scrolling a gallery of images
Don’t move and select, but select by moving

Let’s get into the code. First we’ll need a new animation curve and a place to store the selected image information:

    public AnimationCurve selectionArea;
    public RectTransform selected;

We’ll use a very narrow spike function, it’s supposed to only be over .75 in the selection area (with respect to the alpha we used all along).

Narrow spike function
Make it larger to have a larger area of selection. Caos will ensue if two images can be both in the area at a time

And to complete the opera at the very end of our refresh image foreach loop we’ll insert this

        if (selectionArea.Evaluate(transformedPosition) >= 0.75f)
        {
            selected = img;
        }

This way only the image that’s been scrolled to the center is in the range for which the selectionArea curve evaluates to more than .75, which means only that image gets selected. It’s important to use a very narrow area so that only one image at time can get selected.

And that’s all for the scroll to select part of this tutorial!

This one was very easy, wasn’t it? So, at long last we are over this whole guide and you now have a fully functional scroll-to-select image gallery that looks fucking awesome! Of course there’s a new tutorial coming soon, don’t lose anything, join my newsletter.

A recap to put EVERYTHING in one place for you to copy-paste:

    public AnimationCurve orderFactor;
    public AnimationCurve positionCurve;
    public AnimationCurve zoomCurve;
    public AnimationCurve selectionArea;
    public RectTransform selected;

    public RectTransform[] imgset;
    public float rotationSensibility = 1f; //how sensible is to swipe input
    protected float alphaStep = 1f; //will host the image-to-image distance.
    public float swipeFieldWidth = 300f;//Total distance from leftmost position to rightmost one
    [SerializeField]    protected float alpha; //the parameter around wich all things revolve
    protected float lastFrameAlpha; //last frame's alpha value
    public CatchSwipe inputSource; //A module to handle input that gives us the net x-axis swipe value
    Dictionary<RectTransform, float> alphaoff = new Dictionary<RectTransform, float>();//a dictionary to store all image's offsets

    [Header("inertia Parameters")]
    public bool useInertia;
    protected float inertia;
    public float inertialDampening = 0.9f; 
    public float inertiaPersistenceFactor = 10f;

    [Header("Magnetizaiton Parameters")]
    public bool doMagnetize = true;
    public float magnetizationMaxForceFactor = 0.09f;
    public float magnetizationRangeAlphaStepFraction = 0.5f;
    protected float magneticForce;

    public virtual void Awake()
    {
        if (useInertia)
            doMagnetize = false;
    }

    public virtual void Start()
    {
        alphaInitialization();
        refreshImages();
    }

    protected virtual void alphaInitialization()
    {
        alpha = 1;
        if (imgset.Length > 1)
            alphaStep = 1f / (imgset.Length - 1f);
        float minAlpha = -(imgset.Length - 1f) * alphaStep / 2f;
        alphaoff.Clear();
        foreach (var item in imgset)
        {
            alphaoff.Add(item, minAlpha);
            minAlpha += alphaStep;
        }
        lastFrameAlpha = alpha;
    }

    protected virtual void Update()
    {
        updateAlpha();
        updateInertia();
        updateMagnetization();
        if (Mathf.Abs(lastFrameAlpha - alpha) > 0.001f)
        {
            refreshImages();
        }
        lastFrameAlpha = alpha;
    }
    protected virtual void updateAlpha()
    {
        alpha = Mathf.Clamp(
                alpha + (Mathf.Abs(inputSource.NetSwipe.x) > 0 ?
                    inputSource.NetSwipe.x * rotationSensibility
                    :
                    inertia + magneticForce), 
                0,
                1
                );
    }
    protected virtual void updateInertia()
    {
        if (useInertia)
        {
            inertia = Mathf.Abs(inputSource.NetSwipe.x) > 0 ? alpha - lastFrameAlpha : inertialDampening * inertia;
            if (Mathf.Abs(inertia) < rotationSensibility / inertiaPersistenceFactor)
                inertia = 0;
        }
    }


    protected virtual void updateMagnetization()
    {
        if ((Mathf.Abs(inputSource.NetSwipe.x) <= 0.001) && (doMagnetize))
        {
            float rest = alpha % alphaStep;
            if (rest < magnetizationRangeAlphaStepFraction * alphaStep)
            {
                if (rest < rotationSensibility)
                    magneticForce = -rest;
                else
                    magneticForce = -rest * magnetizationMaxForceFactor;
            }
            else if (rest > alphaStep * (1 - magnetizationRangeAlphaStepFraction))
            {
                if (rest < rotationSensibility)
                    magneticForce = rest;
                else
                    magneticForce = (alphaStep - rest) * magnetizationMaxForceFactor;
            }
        }
    }

    protected virtual void refreshImages()
    {
        List<KeyValuePair<RectTransform, float>> orderingLayerList = new List<KeyValuePair<RectTransform, float>>();
        foreach (var img in imgset)
        {
            float transformedPosition = positionCurve.Evaluate(alpha + alphaoff[img]);
            img.localPosition = Vector3.right * (transformedPosition * swipeFieldWidth - (swipeFieldWidth / 2f));
            img.localScale = Vector3.one * (zoomCurve.Evaluate(transformedPosition));
            orderingLayerList.Add(new KeyValuePair<RectTransform, float>(img, orderFactor.Evaluate(alpha + alphaoff[img])));
            if (selectionArea.Evaluate(transformedPosition) >= 0.75f)
            {
                selected = img;
            }
        }
        var orderByVal = orderingLayerList.OrderBy(kvp => kvp.Value);
        foreach (var item in orderByVal)
        {
            item.Key.SetAsLastSibling();
        }
    }

And this finally ends this lenghty tutorial. I hope you will find it useful 🙂
Tell me what you think about it and follow me on twitter for more useful stuff.

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •