Event Delegation in Unity

What is Event Delegation?

“…a helper object, known as a delegate, is given the responsibility to execute a task for the delegator
– Delegation Pattern Wikipedia

Why use Event Delegation?

A good practice when working with Unity (or any framework) is to decouple your UI logic from your game logic. It’s fine to have the UI code reach down to the game logic layer and call methods directly on it but having the game logic layer directly call methods on the UI logic’s layer is, in general, a bad practice because doing so “marries” you to whatever UI you are currently using. So to get around this we can use C#’s Delegates and Events to fire off methods throughout our UI and even on the game logic layer.

How to use Event Delegation with Unity

All we have to do is:

  • create a static Event Manager class
    • Add delegates and events to this Event Manager
  • Listeners will add functions to the events
  • Delegators will fire off the events

The Manager: Defining events

public class EventManager {
    public delegate void EnemyHovered(int laneIndex, int targetRange);
    public static event EnemyHovered EnemyTargetedRequest;
    public static void EnemyTargeted(int laneIndex, int targetRange) {
        if(EnemyTargetedRequest != null) EnemyTargetedRequest(laneIndex, targetRange);

In this example we create a delegate with the type EnemyHovered which takes the arguments laneIndex and targetRange. Then we make an event EnemyTargetRequest which is the event that the listeners will subscribe functions to. Finally, there is a static method that can be called by delegators when they want to fire off this event, triggering all the functions that are subscribed to it.

The Listener: Subscribing to the event

In another class we can add the following:

void Awake() {
    EventManager.EnemyTargetedRequest += DoSomething;

public void DoSomething(int targetedIndex, int targetRange){
    // do something

In this class we define some function called DoSomething that takes the same arguments as our delegate. In the Awake() method we add the function to the static class’s EnemyTargetedRequest event.

The Delegator: Firing off events

In yet another class we can do the following:

public void OnPointerEnter(PointerEventData eventData) {      
    EventManager.EnemyTargeted(_index, _targetCount);

Here we’re just using Unity’s OnPointerEnter event as the UI event that will trigger our EnemyTargeted event. Because our Listener class subscribed it’s DoSomething function to the EnemyTargetRequest event when SignalManager.EnemyTargeted is called it will fire off the DoSomething function!

So with this, you can keep all your events off in the static Event Manager, subscribe to them when you need an object to react to an event and fire off the events whenever you need to which allows you to keep UI and game logic separated. You could even have GameObjects subscribe to events and unsubscribe from them as they are created and destroyed which is very useful when these objects are created and destroyed dynamically.


Twitch Streaming Game Development

I’ve recently started streaming some parts of Nano’s development on my Twitch channel at http://www.twitch.tv/munkeyxis and you can follow me there to get notified whenever I stream. There isn’t any scheduled time which I’ll be streaming, just whenever I have the time to work on the game for a bit.

I did a couple streams over the weekend and it went pretty well. Even with my petty number of viewers there was still discussion in the chat about coding, Unity and some aspects of the game itself. I’m going to try and provide some tutorial-ish commentary during my streams along with insight into some of the design choices.

The topics covered while streaming so far:

A map that allows for player movement when map tiles are clicked: http://www.twitch.tv/munkeyxis/b/662025812

Creating a Hearthstone-like Inventory/Deck UI in Unity, Part 1: http://www.twitch.tv/munkeyxis/b/662361477

Each of these topics will have a blog post associated with them, those are coming soon. Next time streaming will be Inventory/Deck UI Part 2!

Nano with Unity: Fresh Start

I’ve started to remake Nano using Unity. Nano will no longer be a browser game, instead I plan to release it for PC, tablet and phones. It’s a bit odd for me to say “release it” as if I’ll ever finish it. It would be really cool if I did and that is the plan but you surely know how these kinds of personal projects go.

So far I’ve got some of the basic UI in place, enough for some testing and experimenting. So far this UI is limited to displaying the player’s health points, a few buttons with placeholder actions and an early take on the inventory system.

Next up will be improving the inventory system and adding the Deck feature. Cards in the player’s inventory can be added to their deck, which is used in Nano’s combat system. Though, before combat can take place Enemies will be need to be added.

So that’s the game plan. I’m excited to be working on this project again, here’s to the hope that it’ll go further and be better than the browser version. It wouldn’t take much to be better than that ol’ thing.

Better Map Generation, Auras and Deck Include Modifiers

Getting back into the swing of things with the project by first implementing Better Map Generation. Like I said in my last post, the world used to be generated totally randomly as a player moved around, causing Mountain terrains to be right next to Forests which are directly next to Tundras, basically all the terrain types where just mixed together.

But now, when a player moves into a new location, with no terrain tile associated with it. The game takes all adjacent terrain tiles into account before choosing one. This causes larger Biomes to exist, hopefully this will make the world seem less random and give some aspect of actually being somewhere in the world. Especially when I get around to adding biome specific events, enemies and effects.

This is just the first step in expanding the terrain generation mechanic, so we’ll see how that goes.

Next up, I started adding in Auras but quickly realized I need to refine the idea. The basic idea is that Auras give you special abilities, and you can only have 3 equipped at a time. These special abilities would give you additional choices during events or alter how some items work. At first I thought they might just be stat modifiers but I scrapped that idea because I was afraid it would move in on the Deck Include Modifiers idea.

So my plan is to leave Auras alone for now and return to them after implementing Deck Include Modifiers. What ARE Deck Include Modifiers you ask? This is a mechanic I’d like to add where including certain cards in your character’s deck result in your base stats being modified, as a means of balancing a cards power.

For instance a FireBall card might do a large amount of damage when played in combat, but simply adding the FireBall card to your deck will lower both your Max Hit Points and your Defence. The overall idea is that by adding certain cards to your deck you have some degree of control over your character’s “class”. Want to be a Mage-like glass cannon? Add in those fireballs and other powerful abilities at the expense of your health and defence. Perhaps add in Armor cards that have no effect when played in battle, but their Include effect raises your base defense so long as the card is in your deck, making you into a Warrior like tanking class.

These are just off the top of my head, so there will probably be many changes as I start to add it in. Which is exactly what I’m about to try to do!

True Deck Validation, Card/Combat Reconjigger, Additional Content!

True Deck Validation, I was being dumb

Last post I started out boasting about how I implemented Deck Validation, but then as I was writing the post I realized it didn’t work at all. Well this time I actually DID make Deck Validation work, by avoiding the problem altogether. Take THAT last post!

So originally I came up with this way of having the deck get checked for its validity after a change was made. Oh and just so you know, an invalid deck is one which has less than 10 cards in it, for now atleast, I may increase the minimum deck size later. But anyway, I quickly realized this was the wrong way to go about it, as a deck could be made invalid (remove all the cards) then the player could just leave the game entirely by closing the browser, upon returning to the game they would be back in the world, with an invalid deck, ready to blow up my game the moment they enter combat and have no cards to draw! Hell no am I letting some deckless weirdo blow up my game!

So basically, I just made it so you could never go below 10 cards, if you try to the game doesn’t apply your change, warns you of such and tells you to add a card before removing one, easy. I wish I thought of that at first.

Making Cards and Combat not suck

After that it was on to making Cards and combat a bit more interesting. Problem was, until now, cards could only make 1 stat change. That was fine when I only have cards like Punch and Kick that do x amount of damage to the enemy, but if that is the most any card can do then the game will get boring really fast. I’m bored just talking about it, so I set out to make more complex card interactions possible.

Cards are now made up of 2 objects, Card and CardEffect, in a One to Many relationship. One Card can have many CardEffects. Each of these effects can have a different target, effect different stats and for different amounts. This allows for new cards such as Thrash, which does a large amount of damage to the enemy, a moderate amount of damage to the caster and lowers the caster’s Defence stat. Complexity, Fun!

There are many other cards like this and I intend to balance a cards with positive and negative effects to make each choice one of risk vs reward. Hopefully this will make combat more interesting. I have more ideas for making cards have interesting effects, even having them affect the character outside of combat!

Speaking of combat, since I changed around how cards work, that meant that I had to go back and refactor my combat methods. This took a while but it really needed it, since I’ve learned so many better practices since first coming up with my combat methods. I still have to add in text generation but that shouldn’t be too hard… (famous last words).

Filling out the games content a bit

Lastly, I’ve greatly improved the workflow involved with adding content to Nano. This is something only admins like myself would ever interact with, but adding content has been something I kept putting off simply because the only way to do it was via SQL statements. Well not anymore! Now I have nice forms that I can fill out and drop down lists with all my enums. Just the other day I added 20 cards and all their effects. Next will be enemies, consumables and events!

So, things are working out pretty well, and I think I’m still on track to have Nano ready to present at DevelTeam’s game jam. Only thing left that I haven’t thought about is how to host the game. I originally planned on just hosting it on my own computer and leaving my comp on for a few days and giving them an IP address, but I’ve started to look around and it seems I can get some temporary hosting setup and just use that for the contest. Better figure that out soon!

Deck Validation and DevelTeam.com Contest

I’ve added ‘Deck Validation’ and it was easier than expected. Pretty much any time I implement something and it works right off the bat I consider it “easier than expected”, perhaps I’m a bit of a pessimist when it comes to my programming skills.

Anyway, I’ve set it up so that a character’s deck must consist of at least 10 cards, any less and the player will be shown a warning message, telling them that they cannot leave the inventory screen without adding more cards…

Actually, now that I think about it, there are plenty of ways to get around this, most likely by accident… hmm, how to deal with this then…

Well, the basics are there, I suppose I’ll just have to check deck validation in more places to cover this.

DevelTeam.com Contest

DevelTeam.com is having a contest for indy games/developers. I’m going to try to enter Nano into the contest, but the deadline for submissions is mid/late august and I can only hope to have the game functional by then, it probably won’t be much fun. I’m more interested in getting some people to notice it and maybe get some other developers and artists to want in on the project. The contest is offering a handful of quality game (most of which I already own) but I’m not terribly interested in winning (I’m sure I won’t win with Nano in it’s current state).

If I do get the game into the contest, I hope people will be receptive to the game in its current super-early stages.

Death and Cascading Delete

Character death logic has been added, when a character’s health reaches zero the character is DELETED along with all of its associated records, such as its inventory and any active combat records. Having a character’s death be permanent is pretty vital to this type of survival, roguelike. It makes the risk vs reward choices that much more vital. Just don’t get too attached to your character and its stacked inventory of food and cards.

But not all is lost, for I have also added the Graveyard. This is where all characters go when they die and simply stores their name, final score and the user they belong to. Having these records allows for a couple of things. First, it allows for a leaderboard to be posted that displays the top scores of characters alive or dead. It also permits me to make a page that a player can visit to see a history of all their old characters, perhaps as a motivator to beat their personal best score, or maybe just a place to go and mourn your passed characters.

I’ve got some ideas for expanding the stored stats but for now, name and score is all I’m holding onto.

When implementing character death I realized I had many records that needed to be removed from many different tables. At first this seemed daunting, not only would I have to remove the character from its table, but I’d also have to remove every inventory item, any active combats the character was in and then every enemy card associated with that combat. That’s a lot of foreach loops removing a lot of records, one at a time.

Luckily, there is a better way and it’s called Cascading Delete which basically means – when I delete this thing Entity Framework will go ahead and delete everything else associated with it. Then it was just a matter of going back to my models and making sure they were associated properly to begin with. So now, all I do it remove the character in question and Entity Framework takes care of removing all the records associated with that character via a Foreign Key. It was nice to go a learn a new trick that makes things like that easier to handle.

But it’s not all death and deletion, there have also been major strides with the visual design of the game, and I’ve done a lot to make all of the interactions with Nano use ajax. Once you enter the game’s World view, that it, no need to do full page refreshing anymore.

The character death logic was the last “feature” I needed to tackle before the game can be played seamlessly. Next I just need to work on the visual presentation layer of things and add some more content. Once those two things are done, I hope to be ready for some very early playtesting.


I got a few pieces of art to use in Nano! Here are a few of the pieces that Koishii Kitty (check out her DeviantArt portfolio).

path to solace Paradise lu the sky

She’s been a friend of mine for years and I’ve always wanted to collaborate with her on a project, so I’m pumped that she was kind enough to provide some scenery art for Nano.

I’ve already added these scenes by Koishii along with a new others she provided. Updated screen shots of the scenes within the game itself are on the way. I’ve just been trying to make the game’s combat, inventory and world screens work with Ajax instead of full page refreshes. Doing that and crushing the bugs that pop up along the way have been keeping me busy.

Implementing Events 2 – Expanding and Frequency

There is still more to be said about Events so here is part 2!

Expanding the Events Feature

If all the game did was pick a random event from a pool of every event, the world wouldn’t seem very… alive…duuude. So, some events should only happen in particular climates (I call them Biomes). For example coming across a pool of water might be something that can happen in any biome but an event like “Falling Tree” might only happen in a Forest biome and not in a Plains biome.

To allow for this Events have a Biome, Terrain and hasPriority property. When the game’s engine creates the pool of available events to choose from it grabs all events that can happen in any biome as well as the events that can only happen in the biome the character is currently in. So a character in a forest biome, Big Tree terrain would have an event pool that contains events that can happen in Any biome, in the Forest biome specifically and events that can only happen in the Big Tree terrain tile.

The hasPriority property is only used if a certain event should always be used in a given terrain tile. Such as a Throne Room terrain tile in a dungeon should always have a boss encounter. That event would then have it’s Terrain property set to ‘Throne Room’ and hasPriority set to True (as that variable is a bool).

Event Frequency

There is also a Frequency property to each event and event reward. This number give some measure of control over which events are more common over others. Not too much to say about that one really. While the concept is fairly straightforward, implementing it was not so simple. So here is what I did:

After creating the initial Event Pool, I had a list of possible events. I then added together all the event’s Frequency properties. I used this number as my MaxRandom number, the maximum number the game could roll when picking an event from the pool. I also made a second list called the Event Pick List which only had 2 properties: Event and SlotID. This list was then populated with a number of entries for each event equal to the event’s Frequency. So, an event with a frequency of 10 would have 10 entries in the Pick List. The engine also applied SlotID numbers in sequence.

For Example:
An event pool with 3 events:
A Pool of Water (Freq. 10)
A Falling Tree (Freq. 5)
Strange Mushrooms (Freq. 5)

MaxRandom = 20 (10+5+5)

Pick List:
A Pool of Water (slotID = 1)
A Pool of Water (slotID = 2)
A Pool of Water (slotID = 3)
A Pool of Water (slotID = 4)
A Pool of Water (slotID = …)
A Falling Tree (slodID = 11)
A Falling Tree (slodID = 12)
A Falling Tree (slodID = 13)
A Falling Tree (slodID = …)
Strange Mushrooms (slotID = 16)
Strange Mushrooms (slotID = 16)
Strange Mushrooms (slotID = 18)
Strange Mushrooms (slotID = …)

Then the random number is picked between 1 and MaxRandom. The number picked corresponds to the Pick List’s slotID and that is the event assigned to the character.

With some form of filtering being applied to the possible events and then frequency being taken into account to allow for common/rare events, when a character encounters an event it will hopefully feel more meaningful.

Implementing Events Part 1 – Being Stateless

I’ve started implementing the Events feature into Nano. So far my posts haven’t been too technical or in depth, so this one might be a bit heavy for some. First, allow me to describe the overarching idea behind Events in Nano.

The Idea

As a player navigates the world they occasionally encounter an Event upon entering a new location. An Event is basically a description of something that is happening and a list of choices about how to react being made available to the player. Once the player has made a choice they are given some type of result, such as stat alterations, finding treasure, or getting into combat with an enemy.

Example Event

A player enters a new location called ‘The Open Plain’. Upon entering this location they are shown an Event screen, for the event ‘A Pool of Water’. This event has a description; “You see a pool of water. It looks clean enough to drink.” and a couple of choices:
Choice 1: “Drink the water.”
Choice 2: “Ignore the pool of water, bugs have probably pooped in it.”

The player selects Choice 1, “Drink the water.” (Ignoring the possibility of bug poop!). This choice results in the character’s Thirst being reduced by 100. Had the player ignored the water, they would not have received that reward. A second screen is displayed given both a description and a breakdown of the results.

“You drink the bug poop free water. Ahh, refreshing!”
Thirst: -100

How to Organize the Data?

So now that we know the overall idea of what we’re trying to do. How do we execute that in code? It’s never as straightforward as you think and even when you’re prepared for it to become complex, it’ll go and get even more complex than that. This is because at this stage of development I’m really building a system, not just a ‘if this, then that’ scenario.

How does the database look?

First I had to figure out how to organize the information in the database. Will the events, choices and rewards all be in one table or would it be better to have a separate table for each event element?

After a lot of thought, I decided on having separate tables for Events, Event Choices and Choice Rewards. The reason is that each of these has a One-to-Many relationship with the next. For example an Event has many Choices and each Choice can have many Rewards. This would suggest that using a separate table for each piece would be the best way to manage them.

Being Stateless

One major pain that I’m always dealing with in this project is that as a web game using MVC4 and standard postbacks (ie. I’m not using Flash) is that this game is Stateless. Most games can save information about the player’s current location, stat values, and what screen their looking at in your computer’s memory, but not Nano. Nano needs to save all these variables in a database and access that database after every player choice.

Being Stateless Allows Cheating

So given the Stateless limitation, how does the player’s choice get sent back to the server? Another problem with being Stateless is that user input cannot be trusted, they could send any value they want back to the server and the server just accepts that value, never thinking that the user might be a big fat cheater! For example, if a player is in combat and clicks the Use Kick button, the link they click actually forms a URL that ends in /UseCard#CardID=3 which calls the UseCard method with CardID=3 (3 being the ID # for the Kick card).

So there you go, that’s how you can try to exploit Nano. During a combat just change the url to have the CardID equal a number of an amazing card like ‘Sword of a Thousand Truths Stab’ and you can use that card even if it’s not in your hand or even in your deck!

Just kidding, you can’t do any of that because I had to take special measures to stop that form of abuse. Again, because the game is stateless, when the user sends a request to use a card with a particular ID I first check to see if that card is in the user’s hand. If not the user will get a message saying it’s an invalid card and then it will taunt them for trying to cheat. But the point is, this is something many games don’t have to be concerned about since they can store information in memory.

Record the Character’s Current Event

Something that is nice about working in this Stateless environment is that it allows the player to leave the game at any moment and when they return they will be right back where the left off. Whether that is standing in the middle of a forest, at a crucial choice for an event, or right in the middle of combat.

But this also means that the game must record everything to allow for this seamless return. For Events, I decided to add a property to my Character records called ActiveEvent this field stores the ID# of the event that the character is currently involved in. Upon page load the game says “Is the character in an event?” If no, then the ActiveEvent field is null and the game displays the location the character is in. If yes, then the game looks up which event it should display based on this ActiveEvent field.

Sum it up

So that’s how working in a stateless environment for a game adds a layer of complexity to the design of the game. I have to think about everything in steps and each step has to end in a single output of information for the player to react to. In the next post I’ll get into making events more interesting by limiting their frequency and availability.