C# Generics and Unity

Using Generics.png

Generics are something that can sound scary, look scary, but you are probably already using them - even if your don’t know it.

So let’s talk about them. Let’s try to make them a little less scary and hopefully add another tool to your programmer toolbox.

If you’ve used Unity for any amount of time you’ve likely used the Get Component function. I know when I first saw this I simply accepted the fact that this function required some extra info inside of angle brackets. I didn’t think much about it.

Later I learned to use lists that had a similar requirement. I didn’t question why the type that was being stored in the list needed to be added so differently compared to when creating other objects. It just worked and I went with it.

It turns out that those objects are taking in what’s called a generic argument - that’s what’s inside the angle brackets. This argument is a type and it helps the object know what to do. In terms of the GetComponent function, it tells it which type to look for and with the list, it tells the list what type of thing will be stored inside that list.

Generics are just placeholder types that can be any type or they can also be constrained in various ways. It turns out this is pretty useful.

Why?

Ok. Great. But why would you want to use generics?

Well essentially, they allow us to create code that is more general (even generic) so that it can be used and reused. Generics can help prevent the need for duplicate code - which for me is always a good thing. The less code I have to write, the less code I have to debug, and the faster my project gets finished.

We can see this with the GetComponent function in that it works for ANY and ALL types of monobehaviours. This one function can be used to find all built-in types or types created by a programmer. It would be a real pain if with each new monobehaviour you had to write a custom GetComponent function!

The same is true with lists. They can hold ANY type of object and when you create a new type you don’t have to create a new version of the list class to contain it.

So yeah. Generics can reduce how much code needs to get written and that’s why we use them!

Ok. So Give Me An Example!

Scene Setup.png

I’ve created a simple scene of various shapes. I’ve created some code that will generate a grid of random shapes… but that’s not the important part.

The important part is that I have four classes defined. The first is a basic shape class that the cube, sphere, and capsule class inherit from. Then each of the prefab shapes has the correspondingly named class attached to them.

Shape Class.png
Not much going on here!

Not much going on here!

All of these classes are empty and are primarily used to add a type to the prefab. I do this fairly often in my projects as it’s a way to effectively create tagged objects without using the weakly typed tag system built into Unity. I find that it’s an easy and convenient way to get a handle on scene objects in code.

But more to the point! It allows us to leverage generics in C# and Unity.

When the shape objects are instantiated they are all added to a list that holds the type “shape" as a way of keeping track of what’s currently in the scene. Instead of just shapes sitting in a grid, these could be objects in a player’s inventory or maybe a bunch of NPCs that populate a given scene or whatever.

You can imagine 2 more exactly like this… Just with “Capsule” or “Sphere” instead of “Cube”

You can imagine 2 more exactly like this… Just with “Capsule” or “Sphere” instead of “Cube”

So let’s imagine you need to find all the cubes in the scene. That’s not too hard you could write a function like the one to the right. We can simply iterate through the list of scene objects and add all the cubes to a new list and then return that list of cubes.

And then if you need to find all the spheres. We can just copy the find cube function and change the type of list we are returning and the type we are trying to match. Done!

And again we can do the same thing with the capsules.

But now we have three functions that do almost the exact same thing and this should be a red flag! We have three chunks of code doing nearly the exact same thing. There must be a better way?

Turns out there is!

Create A Generic Function

The only difference between the three functions we’ve created is the type! The type in the list and the type that we are trying to match when we iterate through the list.

Multiple Generic Arguments.png

We are doing the same steps for every type. Which is the exact problem that generics solve!

Find Al Shapes of Type.png

So let’s make a generic function that will work for any type of shape. We do this by adding a generic argument to the function in the form of an identifier between angle brackets after the function name and before any input parameters.

Traditionally the capital letter T has been used for the generic argument, but you can use anything. It’s even possible to add additional generic arguments. They just need to be separated by commas. Some sources will suggest using T, U, and V which will work but doesn’t necessarily allow for easily readable code. Instead, another convention is to start with a capital T and follow it with a descriptor. For example TValue or TKey. Whatever makes sense for your use case.

This generic argument is the type of thing we are using in our function. Which for our case is also the type stored in the list and is the type we are trying to match. So we can simply replace the particular types with the generic type of T.

Do note that we still have the type of “shape” in our function. This is because the list with all the scene objects is storing types of shape so in this case, that type is not generic.

In my example project, I have UI buttons wired up to call this generic function so that cubes, spheres, and capsules can be highlighted in the scene. Each button calls the same function, but with a different generic argument.

Shape Select Buttons.png

The result? We have less code, the same functionality AND the ability to find new shapes if new types are added to our project without having to create significant code for each type of shape.

Generics Constraints

You may have noticed that I snuck in a little extra unexplained code at the top of our generic function. This extra bit is a constraint. By using the keyword “where” we are telling the compiler that there are some limits to the types that T can be. In this case, we are constraining T to be the type Shape or a type that inherits from Shape. We need to do this otherwise the casting of the object to type T would throw an error as the compiler doesn’t know if the types can be converted.

Destory Objects of Type.png

Constraints can be very wide or very narrow. In my experience, constraints to a parent class, monobehaviour, or component are very common and useful.

Without a constraint, the compiler assumes the type is object which while general there are limits to what can be done with a base object.

For example, maybe you need to destroy objects of a given type throughout your scene. This isn’t too hard to do, but a generic function does this really well.

The function “find all objects of type” returns a Unity Engine Object which is too general. If we constrain T to be a component or a monobehaviour we can then get access to the attached gameObject and destroy it.

(Link) You can find more about constraints here.

Another Example

Shape of Type Under Mouse.png

In my personal game project, I often need to check and see if the player clicks on a particular type of object. There are certainly many ways to do this, but for my project, I often just need a true or false value returned if the cursor is hovering over a particular object type.

Check for Object Under Mouse.png

This is again a perfect use for a generic function. A raycast from the camera to the mouse can return a raycast hit. If that hit isn’t null we can then check to see if the object has a component. Rather than check for a particular component, we can check for a generic type. Note once again we need a constraint and that the generic type needs to be constrained to be a component.

Then to use this function we simply call it like any other function but tell it what type to look for by giving it a generic argument. Not too complex and definitely re-usable.

Static Helper Class

Additionally, many generic functions can also operate as static functions. So to maximize their usefulness, I often place my generic functions in a static class so that they can easily be used throughout the project. This often means even less code duplication!

Generic Classes

Generic Class Example.png

So far we’ve looked at generic functions, which I think are by far the most common and most likely use of generics. But we can also make generic classes and even generic interfaces. These operate much the same way that a generic function does.

The image to the right shows a generic class with a single generic argument. It also has a variable of the type T and a function that has an input parameter and a return value of type T. Notice that the type T is defined when the class is created and not with each function. The functions make use of the generic type but do not require a generic argument themselves!

Do note that this class is a monobehaviour and as is Unity will not be able to attach this to a gameObject since the type T is not defined.

However, if an additional class is created that inherits from this generic class and defines the type T then this new additional monobehaviour can be attached to a gameObject and used as a normal monobehaviour.

The uses for generic classes and interfaces highly depend on the project and are not super common. Frankly, it’s difficult to come up with good examples that are reasonably universal.

Object Pool.png

An imperfect example of a generic class might be an object pooling solution where there is a separate pool per type. Inside the pool, there is a queue of type T, a prefab that will get instantiated if there are no objects in the queue plus functions to return objects to the pool as well as get objects from the pool.

The clumsy part here comes from the assigning of the prefab which must be done manually, but this isn’t too high of a price to pay as each pool can be set up in an OnEnable function on some sort of Pool Manager type of object.

Pool Manager.png

This class is static and is per type which makes it easy to get an instance of a given prefab. In this case, we are equating the type with a prefab which could cause problems or confusion, so just something to be aware of.

Generics vs. Inheritance

It turns out that a lot of what can be done with generics can also be done with inheritance and often a bunch of casting. And it might turn out that generics are not the best solution and using inheritance and casting is a better or simpler solution.

But in general, using generics tends to require less casting, tends to be more type-safe, and in some cases (that you are unlikely to see in Unity) can actually perform better.

(Link) To quote a post from Stack Overflow:

You should use generics when you want only the same functionality applied to various types (Add, Remove, Count) and it will be implemented the same way. Inheritance is when you need the same functionality (GetResponse) but want it to be implemented different ways.

Steam Workshop with Unity and Facepunch Steamworks

Adding workshop functionality to a game is something I’ve wanted to learn to do for a long while. I dreamt of doing it with my first game and every project since then. There seemed like there were so many sticking points and potential problems. As I see it there are two main problems.

  1. Not only do you have to create the tools to make that content you have to create the framework to handle that content… While that may sound easy, I don’t think it is. At least for most games.

  2. The documentation on how to implement workshop functionality is scarce. Really scarce. At least from my searches. I’ve found almost NOTHING.

screenshot ac17b53e-8d59-45a3-8e54-410b276034a7.png

With Where’s My Lunch it was easy to figure out the type of content. Levels!

I already had a sandbox level built into the game, so turning that into a level editor really shouldn’t be too much of a stretch. In my earlier post, I explained how I’m using “Easy Save” to save all the data from levels and store it as an external file. It’s surprisingly simple… even easy. ;)

With the type of content and a simple (singular) external file the first problem is largely solved.

The second problem that of the lack of documentation… Was seemly solved by using Facepunch Steamworks. Well, sort of.

Facepunch, provides some code snippets of how to upload and update a workshop item. It looks pretty simple. And it is, sort of. As always the problems lie in the details. And those details can often depend on your projects needs and structure.

Disclaimer & Goals

The main goal of this post is to give an example of how I implemented the Steam Workshop and not to give a step by step process for you to follow exactly - I actually don’t think it’s even possible since every game is so different.

I’m going to try to talk about big ideas and point out the problems I had along the way. I’ll look at how to upload, download and update your workshop items.

These are things that any and all implementation of the Steam Workshop will need to do - at least I think so.

Now, I’m not going to look at how to handle the data and files that are uploading and downloading inside of your project as that’s almost 100% dependent on the type of files and how they’re being used in the individual project

I’m also sure there are some better ways to do what I’ve done. That’s just the way it is and I’m okay with that. If you know of a better or easier way, leave me a comment, I always love to learn something new!

One last thought. When it comes to topics like this… well… there is only so much hand holding that can be done. If you are just getting started with Unity and C#, to be honest, this probably isn’t something that you should be trying to do until you get more experience.

Setting Up the Backend

There’s a not that NEEDS to get set up in Steamworks, but there are a few things. And! They are not covered in the Facepunch Documentation.

Workshop.png
Enable UGC.png

First, we need to enable UGC file transfer, which is done with a single toggle.

Easy.

Workshop Visibility.png

Next, we need to set the visibility state. The default setting will be enough for you, the developer, to upload files, but if you want your audience to be able to test the workshop your going to need to do more work. For early testing I choose the second option, which requires a custom Steam group for your testers. Anyone in that group will automatically have access to the workshop. Which option you choose is, of course, up to you and your project’s needs.

THEN! There is one more important step.

If you are uploading images or larger files you need to enable Steam Cloud and increase the byte quota and number of files per user. In the Steam Developer forums the Valve employees seemed to be in favor of raising the limits far high than expected - which I imagine is to avoid errors and player frustration. I have no idea why the default is so low.

If you don’t change these settings your uploads will fail and there will be no indication that this is the problem. I didn’t hit this snag originally while uploading small save files, but once I added preview images the uploads started failing.

SteamCloudSettings.png

And I spent hours! Hours! Trying to figure out the problem. So yeah. Go change those settings before you go too far.

There are of course other settings but these are the basics that are required.

Uploading!

This is an exciting step. And not a hard one… If it works.

Facepunch and of Steamwork gives almost no indication for the cause of problems if there are any. So yeah. Find some patience and be prepared to spend some time searching for solutions.

The example given by Facepunch is a pretty good start. It’s easy, but with minimal feedback there are a few pitfalls.

Below you can see the upload function that I’m using. I’ve minimized lines that are overly specific to my project.

Workshop Upload.png

To upload you will need a path to the folder containing all of the files and assets. For the file preview image you will need a path to the actual file that will be uploaded.

ProgressClass.png

After that the code snippet from Facepunch shows what you want you need to do. There are several parameters or options for the upload, that while not well documented are named well enough to figure out most of them. For my purposes I added a description, a few tags and set the visibility to public. If you don’t set the visibility to public, the upload will succeed, but the it will be set to private by default.

You may also notice that I’ve created a new instance of the Progress Class. For the most part my version was taken straight from Facepunch, with the addition of a few clumsy bits that will provide some visual feedback to the user while their files are uploading.

The uploading process is asynchronous, so after the upload process has been attempted I send a message to the console based on the results. The results, don’t tell you much, beyond whether the upload was a success or not.

I really wish there were more clues to why an upload may have failed…

If the upload did fail, I display a message to the user and then invoke an event to make sure all the systems that might care about a failed upload know it happened.

It takes a few minutes, but assuming the upload is successful, your workshop item will appear on the game’s workshop page.

Pretty sweet and not too hard.

Downloading

The idea behind downloading is to do a search, then based on the results of that search individual workshop items can be queried or downloaded.

Once again, the Facepunch documentation is pretty good and the process of doing a search is fairly straightforward. In my code, I search by tag and then have other optional searches that can be added by the player.

The search also requires a page number. By default I get the first page, but it’s likely you will want additional pages and you will need to handle this in your implementation. In mine I repeat the search and increment the page number when the player scrolls to the bottom of the list.

Get Workshop Level List.png
Workshop Search Options.png

I choose to wrap the search options in a class for convenienceand to reduce the number of input parameters in the class. While I included many of the possible search parameters, I didn’t include all of them but this custom class will allow me to easily add new parameters without breaking the search functions.

Just like the upload process the search process is asynchronousand the results will come back in a short period of time so it must be done in an “async” function and wrapped in a try/catch.

It’s possible that the results are empty and Facepunch provides a “hasValues” property that can be used to ensure or check that the search was successful.

Do Search Function.png
Iterate Through Search Results.png

Then the results, if there are any, can be looped through with a foreach loop like so.

Displaying Workshop Item info

Displaying Workshop Item info

How exactly you handle those results is of course up to you. Steamworks.Ugc.Item type gives you access to the title, description, votes by the community, a url to the preview image and a whole lot more. Accessing these properties is straight forward, but once again the handling of those values is very much dependent on your project.

To the right (ish) you can see my user interface for each workshop level. The buttons on the bottom right are contextual and change visibility depending on the status of the item. There are also download and delete buttons that are currently hidden and will appear when they can be used.

The actual downloading of an item is quite simple and easy. Items are downloaded by Steam ID which is readily accessible from the workshop item. The files are downloaded to folder in a Steam library. There location can be found with the “directory” property of the Steamworks UGC Item.

Download Workshop Item .png

Do note that you are not downloading a Steamworks UGC Item type! You are downloading the same files you uploaded.

This caused some struggles on my end. It was easy for me to think I no longer needed reference to the Steamworks UGC Item and just work with the downloaded files. Once you lose reference to the item there is no (easy) way to find it again from the downloaded files. By losing reference to the item you lose access to lots of metadata that you’re probably going to want.

So tracking or keeping reference to an item is important and many of my functions pass references to items not the saved files. It’s okay if that doesn’t make sense… I think it will once you start implementing your own solution.

To Subscribe or Not To Subscribe?

So maybe I’ll show my ignorance with the Steam Workshop, but I was under the impression that I didn’t need or want to subscribe to each and every level that a user might want to try out. In the API downloading and subscribing are different actions. I couldn’t find anything that said you should do both…

So here’s me saying I think you should do both!

It keeps things simple and is one less “thing” that needs to get checked. There was some snag I hit… to be honest I can’t remember what exactly it was now, but it was going to take a lot of work engineer around not subscribing. So yeah. Just do it. It’s easy and personally I don’t see a downside for the player.

Updating Workshop Items

The last big hurdle with the workshop was updating items... Once again, the actual updating is pretty straight forward and is very similar to the uploading. The biggest difference here is that rather than create a new community file we are passing in the Steam ID of the item which allows Steamworks to update the files.

Update Workshop Item.png

The one big snag I hit was that the update will fail IF the file has not changed. There’s no indication that this is the problem, the files just won’t upload or update. Which makes sense but leads me to the next issue…

In WML players can locally save a level and don’t have to upload it. This makes sense to me on a lot of levels and I’d venture a guess it’s how most games do it too. But this means that there could be a local version and the downloaded workshop version in different folders… On top of that there’s no easy way to compare those files or know if one exists and the other doesn’t. It seemed to get messy in a hurry.

So if a player makes changes to a level, which version should it save to?

Hmm. Maybe this is obvious, but I definitely needed to think about it for a good while.

I came to the conclusion that changes should always be made to the local versions. And those local versions would need to get pushed to the workshop. This means if a user downloads someone else’s item then before they can edit it a local version is saved.

Check Ownership.png

It’s also unclear to me whether Steam itself checks ownership, so I created an internal check of the item ownership before updating. If the original item is not owned by the current user the files are uploaded to the workshop as a new item. If the original is owned by the player the files update. This leaves out the edge case of the owner wanting to upload the files as a new item, but I’m okay with that.

Deleting Items

Delete Workshop Item.png

It’s quite possible that users will want to delete an item that they’ve uploaded - this is especially true if you are doing some testing with the workshop. And it’s once again very easy. One function call with the Steam ID and it’ll get removed.

The process does take some time and could cause some issues if the user refreshes the search as the item seems to be partially still there for up to a minute or two. For WML, I have the imperfect solution of turning off the UI object when a level is deleted. This gives the user some indication that the deletion is happening, but if they refresh the search I don’t have a system in place (yet) to not show the partial and confusing results.

Conclusion

In the big scheme of things that’s really not that complicated. The amount of code needed to upload, download and update files is actually quite small. The bulk of my code is handling the UI or controlling the input and output of these functions - I’m happy to share those bits, but they are highly dependenton the game and I’m not sure they are particularly useful. But I could be wrong.

Simple Level Save and Load System (Unity Editor)

One of the best things about game jams is the creativity that they require or even force. With such little time to make a game the developer has to get creative to save time. In my case with “Where’s My Lunch?” creating levels was a big bottleneck!

Creating individual scenes for each level was out of the question and frankly, I’m not convinced it would be a good plan even if I had more time. What happens if I need to change the UI? What if I want to redesign the layout? Sure I could use prefabs, but how much easier would it be to just have one scene and then load in the parts for different levels? No juggling scenes. No “scene manager.” Just simple data files with all the needed info for a given scene.

Yes! That’s the way I want to do it.

And that’s how the level save and load system for “Where’s My Lunch?” was created. Now to be SUPER CLEAR, the basic setup does NOT save data during runtime. Not even close. This can only save data in the editor. But! It can load data both in the editor and during runtime. Which for my purposes made it pretty perfect and I suspect pretty perfect for lots of projects.

Looking for a save/load system that works at run time? Stay with me. I use the asset “Easy Save” to convert my system rather painlessly to do just that!

The overarching idea is that the scene is made up of various gameObjects (duh!). The code on each object stays the same from level to level and the only real difference between levels is the positioning and the number of objects…

Which I think maybe true of an awful lot of games.

The Big Idea

Save+Level+Object.jpg

So all the system needs to do is record the position and the type of object. The data for each object then gets stored in a list. This list can be easily accessed to load the level whenever we need it. If that list then gets stored on a scriptable object we’ll get a nice project asset for each level in the game.

Pretty simple and pretty slick!

Or at least I think so.

Finding and Saving Objects

To keep things easy I created a monobehavior that can go on every scene object that needs to be saved or loaded. The class has just one field, which is an enum that identifies what type of object it is. This enum will be used by the loading function to locate the correct prefab.

Level+Manager+Collapsed.jpg

Then all that needs to happen is to search the scene for that type of object and we get a list (array) of objects to be saved. This all happens in the “Level Manager” class. Or specifically in the “Save Level” function.

Do note that this function is never called because I’m using Odin Inspector to create buttons that can be used from the editor. If you haven’t heard of Odin (full disclosure, I work for them) it’s a pretty amazing tool and in this case, is saving me a lot of time by not having to create a custom inspector script!

The save level function from the “level Manager”

The save level function from the “level Manager”

If you don’t have Odin and don’t want to create a custom inspector you can always use the old trick of using a boolean and checking the value of the boolean in the update function. Use this in combination with the “Execute In Edit Mode” attribute and you can get similar albeit clumsier functionality.

It’s also worth noting that In the “Save Level” function we clear the level before saving it. This ensures that we only save one copy of the level and don’t duplicate objects in our list.

After that, it’s just a matter of iterating through the list (array) of Save Level Objects and adding them to the list on the current game level.

Storing Objects

Once the objects have been found we need a place to keep them. And that happens in the “Game Level” class.

The Game Level class is a scriptable object which means that the Game Level objects will be project assets and that makes them easy to handle in so many ways.

Game+Level.jpg

If you aren’t familiar with SO’s check out this video I made for the Odin channel. It’s pretty good if I don’t say so myself.

The game level object is pretty simple. It has a list of “level object info” that will contain an enum of the object type and the position of that object.

There are also two important functions. The first clears the list of objects, this was used in the “Save Level” function on the level manager. The second is to add a level object. This creates a new level object, injects all the needed data to the class constructor and finally adds the level object to the list of level objects.

Level Object Info.png

The last two additional functions are specific to WML and just provide an easy way to get the position of the sandwich and the player.

If we take a look at the “Level Object Info” class, we’ll see a constructor that takes in the “Save Level Object” (which is a monobehavior) and stores the needed information. Do note that there is some special handling of the portal or teleporter - this is due to the structure of the prefab and that the portals come in pairs that are parented to a third “portal pair” object.

Also note that the Level Object Info class is NOT a monobehavior. This class exists only in the list on the scriptable object.

Loading Objects

Save Level Prefab.png

Up to this point, things aren’t too complicated. Sure there are a handful of similarly named classes and you could definitely criticize my naming, but the big idea isn’t too tough to understand. And when it comes to loading the objects, it’s still not too bad but there are a few additional complications.

The biggest issue is to link or connect the object type with a prefab. To do this I wanted a strongly typed connection, not some janky switch statement or block of if statements that are based on the wall objects being the third prefab in a list and the bomb is fifth…

No to that on so many levels! That will 100% for sure break.

It’s going to take a little effort to make this work.

I created yet another class that will contain the enum for the type of object and a reference to the corresponding prefab. This class is the “Save Level Prefab” class.

You can see a list of this type above in the Level Manager. This list will hold references to the prefab that corresponds to the level object type.

You can populate this list manually or (again) if you have Odin Inspector you can use some of their magic to populate it automatically, but I’m going to skip that part for the sake of clarity as it doesn’t really add to the overall concept.

Load Current Level Function.png

So at this point, we have a list that connects the “level object type” to a correct prefab. All we still need to do in order to load the level is to it iterate through the list of “level object info” and instantiate the prefabs.

So, in the “Load Current Level” function we double check that the current level isn’t null, clear the current level (i.e. the scene), and then iterate through the list of level object info that is saved on the scriptable object. For each level object info, we then iterate through the list of save level prefabs to get the corresponding prefab.

Now, there is certainly some inefficiency to this method. I think creating a dictionary might be a better idea - since dictionaries are faster at lookup than lists. The dictionary could use the “level object type” enum as a key and the object prefabs as the value. The hitch to this plan is that dictionaries are serialized by Unity. However! Dictionaries can be serialized with Odin Inspector which means you can add prefabs in the inspector ;) I might make this change down the road, but for now, the inefficiency isn’t a problem as a few extra milliseconds to load a level won’t be noticed and levels might at worst have a couple of hundred objects. So if it’s not broken I’m not going to break it.

Also using an object pooling solution could also improve performance, but once again this is happening once we level and not while the player is trying to do anything so a small lag spike isn’t currently an issue I need to design around. If it does become an issue, it should be easy to bolt on a system.

Load Level Function.png

Extra bits

You may have noticed that there are two other functions in the level manager. A load level function and a clear level function.

The first is a public function and can be called to change the “current level” and then load that new current level. Nothing too fancy.

Clear Level Function.png

And the second simply clears the current level by iterating through all the Save Level Objects in the scene and destroying them.

Runtime Save = Easy Save

The system as is works really well. This is if you are doing all your saving and loading in the editor - which for the game jam I was doing exactly that.

But I want to go further than that. I want to allow players to design and share levels via the Steam Workshop. This means I need a way to save data at runtime and scriptable objects can’t do that - they can appear to, but trust me they won’t work.

I purchased Easy Save from the asset store a few years back and while it might be overkill for this project - it’s really easy to use and saves all the data to an external file AND will work at runtime so it’s ticking all the boxes.

Custom Types are easily added to Easy Save which allows all of the fields of a class to be saved. Data is saved by type and with a key to look it up later. It’s possible to save an entire class, i.e. the Game Level scriptable object, which is going to make things surprisingly easy! Adding custom types is done in the Easy Save editor window.

Notice the 1 line save functionality!!

Notice the 1 line save functionality!!

With that done it’s simply a matter of creating an instance of the Game Level scriptable object and populating the fields with the correct data (hidden in the WML specific data region). Then in one line, we can save the Game Level data to a file of our choosing!

Seriously! If that’s not worth the money for Easy Save? I’m honestly not sure what is?

Easy Load

Could it be easier?

Could it be easier?

Loading the data back into the game is a slight bit tougher, but still not hard. We need to check that the files exist, if not then we stop what we’re doing.

If the file does exist we check for the “level data” key and if that exists we can clear the level, load the data into the game level object and then simply call the same “Load Level” function we did before.

Note: The last line of the function is for legacy support since I made some significant changes to the save system and there are a few levels already on the Steam Workshop ;)


Command Pattern - Encapsulation, Undo and Redo

Programming folks (otherwise known as “programmers”) often talk about encapsulation - which can be a very power concept and tool that can save plenty frustration and prevent bugs as a project grows large.

The idea of encapsulation is that a class or a system has everything it needs to function INSIDE of itself - it doesn’t need to reach out for references and is not dependent on other classes or systems to function. Encapsulation decouples classes and systems. The coupling of systems or classes should generally be avoided to keep your project stable and robust as it grows and has features added.

The command pattern is all about sending information, or a command, to an object. In the case of the command pattern the command itself is encapsulated! The sender and the receiver of the command are not necessarily encapsulated, but rather the command itself is. 

This means that all the information needed to execute that command is wrapped up inside a command class. What this means is the object executing the command doesn’t need any external references - all it needs to do is tell the command to do its thing and the command is fully independent and decoupled from other systems! 

While this requires some framework and intentionally to create - it can be very useful. It means that commands can be added to a list or queue, run immediately, or run at any later time. This adds or allows significant functionality that would be difficult to achieve with just direct function calls.

This makes it great for asynchronous applications - one example might be a turn-based strategy game where a sequence of commands is created one at a time and then all the commands, or a select number of commands, can be run when it is that object’s turn. 

The command pattern can also be used to “easily” create of an undo system - which depending on your project might be helpful or even crucial.

For this post (video), we’re going to start simple. Just using the command pattern to collect commands in a list and execute them over a short time interval. We’ll then add in the ability to undo and redo commands. This will result in some messy code, but we’ll finish up the post by wrapping all that messiness into a “command handler” class - which ends up pretty clean and tidy due to the encapsulation of the commands. 

The Code Begins!

The Command Interface

The Command Interface

Again, the core idea of the command pattern is to encapsulate the command in an object. To do that we first need to create an interface that will have two functions. The first function is the “execute” or “do” function. This will contain all the code for the command to complete its action.

The second function is an “undo” function - which will need to have code that reverses or undoes whatever happens in the execute function. 

Exactly what the undo function looks like is 100% dependent on what the command is doing.

With the interface complete, we then need to create classes for the actual commands. 

The Move Command - Which Implements the Command Interface

The Move Command - Which Implements the Command Interface

For the purposes of this video, I’m just going to create one command which is a “move command.” This class will of course need to implement the command interface.

In the move class, we need three variables. The first is the direction to move, the second is the distance to move and the third is the transform that will be moving. All three of these variables are private and will have their values set in a constructor.

By doing this, the command instance will have all the information and references that it will need to execute the move command. 

This is pretty clever in its simplicity. It’s also pretty clean!

The Execute and Undo functions are fairly straight forward in that they change the position of the transform. The execute moves the transform in one direction and the undo moves it in the opposite direction.

Simple and tidy. Just the way I like it.

I’ve also included a “get move” function that is used in order to draw the path taken by the object - this certainly isn’t the only way to do it. It’s not particularly clean, but it gets the job done and it’s not the focus of this video. For the most part I will be ignoring the path drawing functionality as it’s tangential at best to the command pattern.

turn Based Input Manager

turn Based Input Manager

To control the object and issue the commands, I’ve created a few UI buttons. These are connected into a basic “input manager.” 

In the start function a listener is added to each button. The direction buttons all call a “send move command” function. While the “do turn” button will call a function on the player object that will execute the list of commands.

How exactly the input is gathered, of course doesn’t matter, but the “send move command” is crucial and does a few important things.

This function takes in the transform to be moved, in this case the player object’s transform, the direction to move as well as the distance to move. The function then creates a new instance of the move command and send the command to the character controller. 

For my example it also adds the command to a UI element that displays the commands on the screen. 

A better approach to sending out these commands would probably be to use the Observer pattern or in other words use events… but I didn’t want to go too far astray from the command pattern and complicate the main idea. If you aren’t familiar with the observer pattern or events - definitely go check out that video it’s easily one of my favorite and most used patterns.

Turn Based Character Controller

Turn Based Character Controller

In our character move class, there is a list of move commands that each incoming command will be stored in. You can see this happening in the “add command” function. 

In general, the list could hold types of ICommand, but in order for my path drawing to work I needed to constrain the list to the more specific type.

For simplicity I’m not showing the code that does the path drawing, but if you want to see that you can check out the full code.

There is then a “Do Moves” function that will be called by pressing the “do turn” button. This function calls a coroutine that iterates through the command list and calls “execute” on a command and then waits a short time before looping through to the next command.

And that’s pretty much it for a basic implementation of the command pattern. You just wrap up the commands which contain everything that needs to happen and ship it off to a list for storage so it can be executed when needed. 

Again, pretty simple, nice and tidy.

Adding Undo

So let’s look at how an “undo” system might work. The command interface and the move command class remain the exact same. No changes needed at all.

Input Manager With Undo.png

The input manager is functionally the same, but now has an option for an undo button. This new button will call a public  “undo” function on the character controller - again not the cleanest implementation and an event would likely be better.

The big difference comes in the character controller script. Here I’ll modify the behavior by now having the player object move in real time as the buttons are pressed. This isn’t necessary for the undo function to work, but I think it makes it easier to demonstrate the undo functionality.

In order for the player object to move in real time, we simply need to execute an incoming command whenever that new command is added. 

Real time Character Controller with Undo

Real time Character Controller with Undo

New to the class is the “undo command” function. This function first checks that there is a command to “undo” by checking the number of commands in the command list, then calls “undo” on the last command in the list and then removes that command from the list. 

Tis is super simple! All thanks to the command interface! 

When I first saw this I was surprised and even a bit shocked how easy this could be. Now of course if the command is more complex than the move command the writing and testing of the undo function will be more difficult and more time consuming.

BUT! 

The interface makes it easy to call that undo function and the inclusion or encapsulation of all the values and references provides a solid framework to create undo functionality.

Redo…

For many games this may be enough, but if you want to also implement a “redo” functionality things are going to get a bit messier - or at least the way I did it. All the changes are made on the character controller. The commands stay the same and the only change to the input manager is to add the redo button and connect it to a redo function on the character controller.

Character with Undo and Redo

Character with Undo and Redo

For a redo system, we could simply not remove commands from the command list and then execute them again when a redo button is pressed. Essentially just working our way up and down the list of commands...

But! And there is a but.

If some commands are undone and then new commands are added this will cause problems as those new commands would just get added to the end of the command list…

SO! 

We need to modify our lists and keep track of which command on the list we currently executing or undoing. So yeah. Sounds simple, and it’s not crazy, but it does get a bit messy.

So the first thing we need to do is add an index variable that can track which command on the list we currently working with. 

Each additional command added to the list, the index will increment up one AND with each command undone the index will increment down one. This means we also need to change which command is being undone to correlate with the index and not just the length of the command list. 

With that all done we now need to add a few lines to our “add command” function. We need to check and see if our index is at the end of the list - meaning we’ve undone some commands and are now adding a new command. 

If it’s not then we need to remove all the commands between our current index and the end of the list by using the “remove range” function.

With this complete, we should be able to add commands, undo some of them and add more commands without screwing anything up. If we were to test this, on the surface we haven’t gained new functionality, but it does mean we can now add a “Redo Command” function. 

This function is actually fairly simple, we do some checks to make sure we won’t get a null command or get an out of range error. And then we simply execute the command that correlates to the value of the index. 

Once again, the interface with the execute and undo functions makes this surprisingly simple  - minus the tracking of the index.

But!

It’s So Ugly!

Command Handler Class

Command Handler Class

There is still some overall ugliness to this solution. I don’t like that this code is in my player controller… The AddCommand, UndoCommand and RedoCommand have NOTHING to do with the player controller they could and should be general and usable with ANY command. This code is generic and should be reusable. 

Remember the whole point of the command pattern was to encapsulate the command… so these functions and the list of commands could be just about anywhere.

So is no need for all this code to be in the player controller AND if you were making a game with multiple types of objects that could all receive commands it would be a pain, and more importantly error prone, to repeat this code in multiple classes. 

So let’s extract the command code and stick it into a command handler class. 

Super Clean!!!

Super Clean!!!

This class contains the list of commands, the index as well as the functions to add, undo and redo commands. Then in the player controller script, we simply need an instance of the command handler class.  

Final Input Manager

Final Input Manager

The final tweak is to reroute our buttons in the input listener to call functions on the command handler. 

If we take a step back, what we have is really clean and surprisingly generic. 

Yes, we do have a lot of classes, but that is often a trade off with our programming patterns and I think cleanliness of the implementation more than makes up for the extra classes.

Due note that this implementation does lose our ability to easily draw the path of the player, but with some cleverness, especially if commands are sent with events, this can be gotten around without too much work.

A few last thoughts…

Like many patterns it’s not the exact implementation that is important, but rather the large idea and framework. While I used direct function calls, I think using events i.e. the observer pattern could be more generic and more powerful. 

The command pattern may result in commands being created and destroyed with some frequency. Which can create unneeded garbage collection. While not a problem with my simple example, it would be possible to implement an object pooling solution to use with the commands if performance is crucial or if you just want to squeeze out a few more FPS out of your game. 

Code

GitHub Link: https://github.com/onewheelstudio/Programming-Patterns

GJTS - Adding Steamworks API and Uploading

So here we go! A new project and a new series! If you have no idea what I’m talking about you might want to check out the series intro video video.

Today’s goal is to get “Where’s my Lunch” working and downloadable on the steam client. And in the process, hopefully give you an idea of what that takes to do it with your game. While getting the entire store setup will take days or even weeks… getting your game on the Steam servers and ready to share with friends or supporters is actually pretty easy.

While it’s not necessary to do it this early in the development process, I want to do it as an exciting first step AND integrating steam at this point seems like a good idea as adding significant functionality early in the development process generally keeps things working smoothly down the road.

Steamworks.png

Steamworks

So if you are trying to follow along, the first thing you need to do is set up a Steamworks account. Now I already have one, but if I remember it’s not too complicated to do it - but you WILL need to provide quite a bit of information and it’s definitely more involved than creating a regular steam account, but very doable and Valve should walk you through the process.

I WOULD strongly recommend that you create a new Steam account too. DON’T use your personal account for publishing games. A layer of separation, even a small one will be appreciated when comments and questions about your game start flooding your notifications. Not to mention that keeping your branding clean and semi-professonal is much easier with a dedicated publisher account.

Personally, I log in with my OWS account in a browser and into the Steam Client with my personal account… This prevents tedious logging in and out while still keeping some separation. I’ve also got the two accounts setup to use family sharing which helps keep things simple in terms of accessing games.

As another side note, many people think they need to start a corporation to publish games… Now I’m not a lawyer, I hope that’s obvious, but please go talk to a lawyer first if you think you need to form a corporation. Taxes and such, at least here in the states, get way more complicated if you form a corporation and unless you start making real money it’s not worth it. 

OWS is registered as a sole proprietorship which has worked perfectly fine over the last few years. And unless I sell 10’s of thousands of copies of this game, it’s going to stay that way for a while longer.

Once you have a steam account you can add an app to Steamworks. And THIS is the part you have to pay for… My first game went through Steam Greenlight, but these days you just have to pony up $100 and you can put your game on Steam.

AppID.png

Once your application is added you’ll see an appID which we’ll be making use of quite a bit so it can be worth writing down or at least leaving the window open. With a Steamworks account you can now get access to the “Steamworks Development” group on steam. 

It’s fantastic. 

Just about every question you’ll have about publishing a game will be on the forum AND if you can’t find the answer you can always ask a new question. Valve has employees that monitor the group and will chime in from time to time when needed. If you’ve never published a game before… you should spend a lot of time reading in this forum. 

It will be worth it.

Picking a Wrapper

The next step in the process is to pick a Steamworks wrapper… The steamworks API is all in C++ and since I’m using Unity, which uses C#, I’m going to need a wrapper or a layer of code to interact with that API. You could write your own, I suppose… but why? 

Don’t do that.

Steamworks Complete.png

For my first game I used Steamwork.NET which I think at the time was the only real option. Nowadays there’s a few more. So, I spent a few hours researching: watching videos, reading posts and articles. 

I found “Steamworks Complete” on the asset store. It uses Steamworks.NET and effectively wraps it in an easier to use package. Watching the videos it seems like the asset is well designed, but in the end, a wrapper of a wrapper to me didn’t seem like the best idea. I’ve grown cautious of using 3rd or 4th party tools…

After all, if I figured out Steamworks.NET several years ago with much less programming experience, I should be able to do it again and I don’t need someone else’s code to help…

I think.

I hope.

FacePunch.png

I was just about ready to download Steamworks.NET, but for some reason I hesitated and did one more google search - the choice of wrapper is something I’m going to have to live with until the project is finished so I wanted to make sure all my ducks are in a row!

And I’m really glad I did. In an article, I found a link and reference to “Facepunch Steamworks!” And oh man, does it look better and easier to use! Steamworks.NET is all in C# but it’s not user friendly or at least not as much as it could be. Facepunch Steamworks is easy to read and easy to understand if you're comfortable with C#. Plus it’s in active development as it’s used in Rust and Gary’s Mod. Which is more than good enough for me. 

Whether it’s true or not I also found a quote from the Steamworks.Net developer that “most people should use Facepunch.” 

Okay. Definitely good enough for me. 

The install process is dead easy, but I did find that locating the link for the instructions for doing so in Unity a bit hidden - but once I found them it’s a simple download and then just a matter of dropping the files into a folder in my project.

Honestly, I can’t imagine it being much easier.

Steam+Manager.jpg

After that it’s just a matter of creating a simple “Steam Manager” and Facepunch provides an example of how to do just that. The steam manager will create a connection with Steam and make sure that the game is getting all the callbacks that it may need - most of this functionality will be needed later as I implement steam features like achievements, leader boards, and hopefully workshop functionality.

Do notice that I added the command “Don’t Destroy on Load” to ensure the steam manager will persist in all scenes. This is quick and easy, but I will likely need to revisit this down the road as returning to the start scene from another scene will create a duplicate copy of the steam manager. Not a big deal at this point, but I’d like to keep things tidy when possible.

Steam Overlay After Initial Install.png

At this point, I wanted to do a little testing. So I made a build. And, sure enough, the steam overlay works AND Steam shows that I’m playing a game. Not a big step, but pretty fun all the same!

Now for the harder parts… I wanted to upload the game to steam and get it functional so I could push out a few keys and let folks play the game. 

The rest of the post (and video) is going to look at how to do that and since I did get it working I decided to add a few Steam keys to the comments below... (Video only)

And if I remember I’ll keep adding keys with each video in the series.  So make sure to get to the next video early! 

If you happen to be a patron or a channel member supporting the channel with $5 or more per month - keep your eyes open as I’ll be looking to get keys into your hands as well. 

Documentation! Probably more than you want to read ;)

Documentation! Probably more than you want to read ;)

But back to the actual point of the video, Valve provides pretty good documentation on how to upload your game to Steam, but still, I managed to fumble around and forgetting a few key steps. Those extra steps are there for good reason and give you, the developer, a bit more fine control on what players have access to and when they get that access. 

So let’s take a look at how to make it all work.

The first step is pretty straight forward, and that’s to set the allowed operating systems. In my case, I’m sticking with 64 bit Windows for the time being.  After that, a depot needs to get set up with the correct OS. Do note that each depo has an ID  number that’ll be needed in the next steps - this number should be related to your appID.

You also need to set up the launch options, which essentially sets the executable file that needs to be opened to play the game.

After that I needed to download the SDK and put it somewhere convenient. Value recommends putting your game files into a folder inside the SDK folders, you don’t have to do this, but it’s not hard so I’m going with it. You could choose to manually move the files with each build OR have the SDK look into different folders… but this seems easiest for now.

The three scripts that need to be edited

The three scripts that need to be edited

I did this by changing where Unity puts the builds and rebuilding the project. 

Next, it’s just a matter of editing three text files to push the game files up to the steamworks backend. These files can be opened in just about any text editor - I use notepad for simplicity. As a tip for those on a windows machine: holding shift while right-clicking should give options to select a program to “open with” if they don’t automatically open in notepad.

The first script we need to edit is the “Depot build” file which can be found deep in the SDK folder structure under “content builder” and then in “scripts.” Here all that needs to be changed is the depot ID which we got when we created the depot.  

In the same folder there is the “app build” file in which you will need to change the appID and  information about the depot build file. 

That last file that needs modification is the “run build” batch file. This file helps streamline the upload process. In this file, you’ll need to put in your username and password - both in plain text but surrounded by quotes.

Then all that needs to be done is to make sure all three files are saved and run the batch file. 

I have two-factor authentication turned on so I got prompted for a code. If you don't have this turned on, especially in your developer account, go do it now! Even if you don’t make money this isn’t an account you want to lose control of.

Now, it might take a while to upload the first time or if big changes have been made but the game is on it’s way to the steam servers!

Sweet!

Now, when I got to this point I was feeling pretty confident and pretty happy. It should all work! 

Right?

The branch build settings

The branch build settings

Well, it didn’t. 

The game showed up in steam, I could even “install” it and press the play button…  But I got an error. I checked the local folders and there wasn’t anything there.

Hmm. What did I mess up?

Well, it turns out there are a few extra steps that I missed. The build branch needs to be set and the changes saved…. That’s easy.

So, confident that I’d fixed it, I did one more test and I still had the same problem. It took a search or two on the development forum to find the problem.

The magic button… “Publish!”

The magic button… “Publish!”

The missing step is to actually publish the build. Go figure.

When you do this SteamWorks makes you type a “password” into a field so that you don’t do it by accident.  Which is good. This is Valve protecting me from myself. And I very much need that.

Remember that  this is potentially going public AND steam will likely auto-update players versions so you want to be REALLY sure that you aren’t doing this by accident and pushing a test build when you aren’t ready.

So! with that last step… It finally works! “Where’s My Lunch” is playable through the steam client. 

Even though I’ve done it before, this feels pretty great. I’m just going to enjoy this feeling for a little while…

Load/Save Manager with some Odin Goodness

Load/Save Manager with some Odin Goodness

In the next post (video) I’ll be taking a look at the level save system and making modifications so it can work with the Steam Workshop. Right now it’s pretty basic, but it saved me enormous amounts of time during the game jam. It allowed me to load, create and save a level in a matter of minutes! It’s generic enough and I think it could work for a lot of simpler 2D and 3D games. So I’m looking forward to sharing that with you.

I’ll also be working to implement the Steam Workshop - which will mean some tweaks and adjustments to the save system as well as creating a the UI to allow the players to upload and download content.

Game Jam... Now What?

When you finish a game jam you’re exhausted, but hopefully you’re proud of what you’ve made. Or better yet proud of what you’ve learned.

And that’s what game jams should really be about. Learning something new. Pushing yourself to create new systems or learn a new technique. And we should celebrate what we’ve learned and the new thing that we created. This is so much more important than how well you may have done compared to others. 

GMTKJame.png

Certainly, measuring yourself against others has its place, I won’t say it doesn’t - I race bikes for fun, but that shouldn’t be your sole focus or measure of your success when taking part of a game jam. 

Which is great and all, but that’s not really what this is all about. I’m not here to give a pep talk. I want to talk about what to do with your game after the jam is over. Should it just gather digital dust never to be played again? Well, maybe. 

But! What if there’s more to learn? What if there’s more to do with that game?

AND THAT! 

That chance - that there’s more to learn and more to do is what this series of videos and blog posts is going to be all about. 

So let’s rewind a bit.

WML.png

This summer, for the Game Maker’s Toolkit game jam I made the game “Where’s my lunch?” It was an okay game. Nothing profoundly creative or groundbreaking - just okay.

And I like many others I planned on leaving the game in a folder and never really looking at it again. 

And then I got a suggestion from a viewer: Why not take that game and publish it? The process could make great video content and be a resource for others who might want to do more with their project. 

Whoa! 

I let the idea rattle around in my head for a few days - then a few weeks. The more I thought about it the more I liked it. 

Over the last year or two I’ve been far more focused on making video content rather than working on my own project. Which means I often just have a few hours a month to work on the game. The progress is slow AND that progress is further slowed by needing to remember what I was doing two weeks ago or what problem I was trying to solve last month. 

It’s not working great. And I suspect some of you know exactly what I’m talking about. It’s really really hard to find 10-20 hours a week to work on a project.

Now by their very nature game jam games are simple. Their scope is small - even tiny - and that makes it perfect for me, and maybe you.  

Game Jam to Steam (GJTS)

We can all dream… right? :)

We can all dream… right? :)

So maybe, just maybe… I can work on a game AND create decent tutorial content for the channel at the same time!

Now, this project isn’t going to make me piles of money - I don’t think that’s even a distance possibility and that’s really not the goal. The goal is to make something, finish that something...  AND! Document the process so that others, maybe you, might do the same thing with your game.

How many of us have dreamt about publishing a game to steam? How many of us have a game from a game jam sitting in a folder that with a few months of polish could be worth sharing with a larger audience? 

Now, I’m not talking about some generic 2D platformer with floaty jump mechanics that was your first Unity project. But I’m also not saying that you need to place in the top 10 of an international game jam. I certainly didn’t!

Out of 5381 games… Not too bad. Not Amazing.

Out of 5381 games… Not too bad. Not Amazing.

Maybe your game needs some redesign or a few tweaks to be it’s best and that’s okay.  “Where’s My Lunch” certainly does. It did well on fun factor and a few other bits but clearly isn’t a particularly original game idea. 

And again. 

That’s okay. 

So let’s do it. Let’s do it together. Let’s take a game from a game jam, polish it and publish it!

Videos Incoming!

For the videos, I’ll be trying to find the sweet spot somewhere between a traditional dev log and a tutorial. All while bringing you along for the ride, showing you my progress, and hopefully helping you make progress on your own project. 

FacePunch.png

I’ll be adding the game to steam (It already is! Just not public.), making use of Facepunch Steamworks, adding Steam features such as achievements, maybe the Steam Workshop, and of course, polishing and expanding the gameplay to add dozens of levels - all hopefully without too much feature creep. 

I’m also looking into several of the features offered by Unity such as analytics and cloud diagnostics...

When there’s a system or process that can be of use to the larger game development community, I’ll slow down and do more of a complete tutorial on how the system works and how I built my version of that system.

Sound interesting? Sound useful? I hope so. 

So Let Me Introduce You…

Okay, doesn’t show much… This is the sandbox level

Okay, doesn’t show much… This is the sandbox level

“Where’s My Lunch” is a hand drawn 2D game that presents a new puzzle to be solved by the player at each level. The goal is to steer the character towards their lunch --- but your controls aren’t very precise.

The theme for the game jam was “out of control” and that’s reflected in some of the chaos of the game play. Your only tools, in the current build, are bombs, portals, and gravity wells. 

The bombs explode and exert a force. 

The portals come in a linked pair and warp the player’s from one location to another.

And the gravity wells, they exert an attractive force based on distance from the player.

Now I WILL be adding to these as I work on the game, but the three mechanics were enough - or in reality it was all I could manage in a 48-hour game jam.

There are of course some bugs that need to get fixed or addressed. And mostly this has to do with placing items.  At the moment it’s easy to place a portal on top of the player and then be unable to move it later. I also need to add a “clear level” functionality to let the player wipe the level and start over with a fresh attempt.

Other things like placing a gravity well near the sandwich seems to make it too easy, but more importantly, some of these flaws allow a player to “break” a level by finding a trivial solution - which is okay, but it can take some of the challenge and thus reward out of the game.

Clever level design is maybe the toughest challenge that I see in completing the game. Puzzle games, I think, are often seen as “easy” to make but the reality is they just as tough or tougher than other genres… But again I need to remind myself that the goal here isn’t to make the most awesome game just to make a decent game.

Down the Rabbit Hole!

Let’s dig in a bit into how things actually work in the game - the mechanics of the game so to speak. 

mw3E5Y.png

Here it’s pretty simple, no surprise, and the game leans heavily on the physics engine - which does have downsides as it’s not fully deterministic - and by that, I mean that two identical starting conditions won’t have identical results - they’ll be close but not perfect.

But that’s a battle for another day, and the built-in physics engine is plenty good enough for my project.

The player object is a ragdoll with a basic bone structure built from 2D hinges. There’s not really any gameplay mechanics here, it’s just a lot more fun to watch the player fly across the screen with the arms and legs flopping all over the place. 

Player.png

Since the physics engine is non-deterministic, I chose to use a large circle collider on the player body as this made the motion of the object more repeatable with just a small loss in floppy ragdoll goodness.

After that, the code is mostly about triggers and a little custom code for each of the tiles or objects in the scene. 

As a fun challenge during the game jam and at the suggestion of a viewer, I added a sandbox level that allows the player to create their own level from scratch. This is one of the systems that I plan on expanding so that players can not only build levels but share those levels! Hopefully using the Steam Workshop functions.

Maybe I’ll even be able to incorporate some player-made levels in the final build…?

During the game jam, I quickly realized that I needed to streamline the workflow for making and saving levels. Having each level in its own scene was going to get messy in a hurry! I needed a better way.

One of the great things about game jams is you are forced to get creative and do so efficiently and as a result, I came up with a simple but effective scene creation system. 

SaveManager.png

My system, which I’ll do a full tutorial on, essentially scans the scene in the editor for game tiles which all have a “save level object” component and then stores the basic transform information for each object as well as a reference to what type of object it is. The data is stored in a list on a scriptable object. 

Since the data is stored in a simple list, I’m hoping this will make using 3rd party tools like Easy Save quick and hopefully relatively painless. The plan is to have each level stored in a separate save file which can, hopefully, be shared between players on the Steam Workshop. I’ve never done any work with the Steam Workshop, so I’m pretty excited about that!

And that’s pretty much it. There are certainly other chunks of code, such as the code that allows the player to wrap around the screen or to trace the path of the player, but those are small details and not core functionality. If you want to see those bits, let me know in the comments below. 

What’s Next?

Where is the game going? What’s going to be added?

ToDoList.png

I’ve got a list of new mechanics that I want to add to the game. These include buttons, levers, doors, flame throwers, ice, electric fields, and whatever else may come up. These mechanics should be easy to add and shouldn’t cause significant changes in the core architecture. 

There are things that WILL require significant changes such as steam integrations like achievements and the steam workshop. 

I’m also exploring the idea of adding more than one goal to the game - to give a bit more depth as the levels progress. So maybe it's not just about getting your sandwich, but maybe you need to grab a drink and chips on your way to your sandwich?

I don’t know exactly, but I do know that I need to build the code for that functionality pretty early in the project as this could affect quite a few other systems.

I’d also like to explore some sort of scoring system to add some replayability to each level. This might be the classic 3-star system or something more numeric on a leaderboard? I don’t know, but again this likely needs to get built sooner rather than later. 

If you want to see the full “road map” for “Where’s My Lunch?” check out the notion page. There’s a list of everything that I’ve planned out so far… in varying detail. It’s a living document and will get updated as the project moves forward.

More Thoughts

But! The real beauty of this project is not how much can be added, but how few major systems need to be created. The game is functional. It just needs to be polished and integrated with Steam.

That’s not to say this is a short or easy project. There is a TON of work to do, but it’s the amount of work and the type of work that is manageable and doable. 

So what do you say? Do you have a small game gathering dust? Why not polish that game and release it? Who cares if you make money? Simply publishing a game to steam is a huge accomplishment in and of itself!!

So go blow the dust off your game AND stay tuned to the channel as this project gets started. 




Strategy Pattern - Composition over Inheritance

The strategy pattern is a subtle pattern. It’s all about minimizing the duplication of code and decoupling classes. As an added bonus, the strategy pattern can also allow behaviors or algorithms to swapped at runtime without any messy switch statements or long chains of if statements. In the end it doesn’t have a super flashy or exciting outcome. It’s just good coding practice.

With some aspects of the pattern it’s easy to think, “Yeah, but this other way works…” But! The pattern is solid and avoids lots of little issues that can pop up later down the road when your project gets bigger.

Before we jump into the pattern lets first look at the problem it solves.

Inheritance Is Not Always Awesome

WeaponBase_Unpattern.png

Let’s imagine you’re making a game based around weapons, or at least has a lot of them in your game. It would seem reasonable to create a “Weapon Base” class that other weapons can inherit from. This base class can contain basic stats and functions that can be used or overridden by sub-classes.

For example, we may have a DoDamage function that gets called every time a weapon is used. The function might simply reduce the health of the player’s target.

This is all reasonable.

Going a step further, let's imagine that we want to create 3 fire-based weapons that will all inherit from the WeaponBase and on top of reducing the targets health will also do some actions specifically for fire damage.

FireDagger_Unpattern.png
FireSword_Unpattern.png
FireAxe_Unpattern.png

I now have 3 new classes that all have duplicated code. The DoDamage function has the same code from the base class, plus fire damage specific parts.  Updating the fire behavior means opening and changing the code in all the every fire weapon class in your project. This isn’t horrible with 3 weapons, but imagine having 20 or 50 or 100 weapons. Yeah, that’s not going to work.

I could also call base.DoDamage, but then all my weapons would be dependent on the base class DoDamage function, which is definitely NOT AWESOME.  If the base class function changes, all the inheriting classes change too and that’s not good. That’s not a solid foundation to build on. That’s a way to break your game in a hurry. This coupling between classes is what we want to reduce!

Now you might now argue that you could create a “Fire Weapon” class that inherits from the weapon base class and that all fire weapons inherit from… Which may work, but it is starting to get messy. Imagine now that you want to add ice or poision damage? You’d have to create Ice Weapon and Poison Weapon classes that those new weapons have to inherit from.

Okay, push comes to shove this might still be okay… Ugly, but okay, if the project stays small.

What if you now have a weapon that will do both fire and poison damage? Which class does it inherit from? Fire or Poison? Or do you make a combo class to inherit from? NO! Please don’t.

The strategy pattern can help solve these problems…

Strategy Pattern

The strategy pattern is all about encapsulating or wrapping up a behavior or algorithm in it’s own class. It’s also very closely related to the concept or belief that composition is better than inheritance! The exact details of how we do this are less important than the overall pattern so let’s start with a simple and common way to implement this pattern.

Interface.png

First, we create an interface called “IDoDamage” (you can argue all you want about using “I” to name an interface - I don’t care). This interface will have one function called “DoDamage.”

At this point, you might be thinking, “Okay, we’ll just implement the interface in all our weapons.” And that would be understandable, but it would be a mistake to do that as that would cause lots of duplicate code and not really buy us much in return from just good old inheritance.

WeaponBase_Pattern.png

Instead, we are going to create an instance variable of this interface in the Weapon_Base class. This class will also have a function that calls the DoDamage function on the IDoDamage variable.

Why? Good question. This is the crux of the whole pattern.

FireDamage.png

We can create classes that implement the IDoDamage interface. Each of these classes will have a different damage behavior. This will encapsulate the damage behavior AND make it so that we can change behavior at runtime by a simple assignment - no ugly switch statement or crazy chain of if statements needed.

For example, we can create a “FireDamage” class. This can do all the basic damage bits and most importantly it can then do any fire specific bits - maybe there are events that play sound effects or trigger specific lighting effects.

Then!

We create a new class for each weapon that inherits from Weapon_Base. Rather than hiding variables or overriding functions we use a constructor to set basic variable values AND to set the damageType variable.

FireDagger_Pattern.png
FireSword_Pattern.png
FireAxe_Pattern.png

While we now have a poop ton of classes, which could be a criticism of the pattern, we have very little duplicated code, and if we need to change the fire damage behavior, it only needs to be changed in one place in our project.

There is a neatness, a tidiness, a cleanliness that just feels good with this implementation. All we are doing is using a constructor to set up the weapon. The entirety of the damage algorithm or behavior is fully encapsulated in another class. While we are still using inheritance, we have decoupled much of our code, and much of the messiness of inheritance isn’t present in our solution.

Adding More Behaviors

The strategy pattern also works if you want to create other types of damage, such as IceDamage. To implement this style of attack, we need to create new IceDamage and IceSword classes.

IceDamage_Pattern.png
IceSword_Pattern.png
GenericSword_Pattern.png

Going Abstract

You could go either further and create generic weapons that have their damage and damage type set by a constructor. This could allow generic classes for each weapon type with all the data PLUS the behaviors injected into it.

Changing Behaviors

And I think the real cherry on top is that with the strategy pattern is that it allows easy changing of behaviors at runtime. Sure, you could do that with some if or switch statements. But those tend to be ugly. They break. They’re generally a brittle approach to programming and we can do better.

ChangeBehaviors.png

We can add a function to Weapon_Base to allow the damageType variable to be set. This would have the effect of changing behaviors. Something the code on the right.

Yes, I realize I made the variables public, but I don’t like changing values in classes from outside the class without using a function. If this was my project, I’d probably use private variables or maybe a public getter. 

With this functionality, a click of a button or the invoking of an event can change the weapon's damage type and thus much of it’s behavior.

If that’s not useful. I’m not sure what is.

Combining Behaviors

MultipleTypes.png

What if you really want that fire poison sword? Maybe your game is based around combining behaviors or abilities? Then what?

Make a list of IDoDamage values. The code can then iterate through the list and called DoDamage on each item in the list?

I’ll be honest I haven’t tried this but it seems solid and pretty useful.

Other Thoughts

The choice to use an interface in the strategy pattern is not the only choice. You may want to use an abstract class instead so that you can define variables. Personally I like the cleanliness of the interface and then simply injecting any needed data.

I also thought to use scriptable objects. And while I think that would work, I think it’s stretching SOs to a place they don’t fit particularly well. Writing the classes and then creating assets seemed like too many steps and I was struggling to find a situation where that would truly be better. But maybe I’m wrong?

I also wrestled with making the base class a MonoBehaviour or not. For simplicity I kept it as a MonoBehaviour so I could easily attach it to a button (for the video). I think that choice really depends on the use, but my gut say most the time I’d want it to NOT be a MonoBehaviour.



Observer Pattern - C# Events

The observer pattern is one of my all time favorites. I use it ALL the time. I’ve shared it with students and they almost immediately see the usefulness of the pattern. It’s not always the easiest to wrap your head around, but it is one of the simpler programming patterns to implement in Unity.

The Big Idea

The observer pattern is all about communication between objects, sharing information and doing so in a way that decouples the object that is sharing the information from the objects that might need or make use of that information.

Score and Achievement System

Score and Achievement System

Using the same example project as for the last 2 programming patterns, let’s imagine that when the NPC kills a critter the NPC’s score goes up and gets displayed on the screen. One way to do this would be to have the critter (or the NPC) call a function or change a value on the UI element. This requires the critter to have a reference to the UI element - some form of “Find Object” or assigning it in the inspector. This works and it’s how many of us did when we first started.

But, what if there is an achievement system too. That system wants to display a message for the first kill, after 5 kills and then every 10 after that? Do you link the critter to the achievement system? Does the achievement system connect to the UI element? What if you have an audio system that plays a SFX each time the score goes up?

You can probably start to see the problem.

And it gets even worse! If the UI element changes or the designer forgets to put the achievement system in the scene then errors will get thrown and the game will start to break.

The result of all of this is a mess of spaghetti code that is highly coupled or inter-connected. If any one piece is missing from a scene the game will likely break. Plus if you change how one element works that could break all the connected pieces. This is a brittle project and will not be easy to finish. And yes, we’ve all been there.

This is where the observer pattern comes in and changes how objects communicate. Instead of all the objects being connected or having references to each other. The critter can broadcast a message that it was killed. Any objects that might be interested can choose to listen for that message (or not) and then do something based on what they’ve heard. The critter no longer cares or is aware of the UI element or the achievement system. If those systems change or aren’t in the scene - nothing breaks. If new systems want to be aware of when a critter is called all they have to do is listen for a critter to broadcast a message.

This is huge! This turns the UI and the achievement system into observers of the critters!

How Does It Work?

The observer pattern is so useful that C# has essentially baked it into the language. That makes the implementation of the pattern quick, but not always super clear or intuitive. So before we get to the implementation we’re going to talk about delegates, events, actions and a tiny bit about funcs. All of these bits are related, connected and useful. If you want to skip the explanation of these bits, you can jump down to the implementation section.

Delegates

I’ve seen few things in C# that seem to confuse folks more than delegates. There’s just something odd or mysterious about them. And admittedly there is a lot going on in the syntax of a delegate. So let’s try to clear some of that up,

And to give credit where it’s due - check out the two part video series by Sebastian Lague on delegates and events. When doing my research, I couldn’t find a better explanation than these two videos. He also goes over a few more or at least different examples that I will.

Delegates can be thought of as a variable that can be assigned a function as a value. A delegate can hold a reference to a function and then the delegate can be “invoked” and the function will be called.

Now that may seem strange. Why not just call the function itself. But you can imagine a scenario where you may want to change what a particular key does when it’s pressed. One way to do that would be to invoke a delegate each time that key is pressed. Then to reassign what the key does you simply have to change the function that is subscribed to the delegate. Easy. And hugely flexible!

But for me the real benefit comes from the fact that delegates in C# are “multicast” delegates - meaning that they can have multiple functions subscribed to the delegate. So invoking one delegate can call as many functions as needed. Add to this the fact that delegates can be made public and even static and that allows classes to subscribe and unsubscribe from the delegate.

And that right there is the basis for the observer pattern!

To keep things grounded, let’s think about what this means for our example project. If our critter has a “CritterKilled” delegate that gets invoked when the critter dies, then our scorekeeping UI element and our achievement system can both subscribe to that delegate. Whenever a critter dies it invokes the delegate which in turn calls a function on the UI element and a function in the achievement system! Each class is in full control of which delegates it listens to. The UI element and the achievement system have become “observers” of the critters!

Basic Implementation

A very basic even silly implementation of Delegates

A very basic even silly implementation of Delegates

To use delegates we must first define the delegate itself. You can see this in the first line of code (after the class definition) on the right. We then need an instance of the delegate - these can be defined locally inside a function or in this case they are defined with a class wide scope. It is this instance of the delegate that will be subscribed to and invoked!

We then need to subscribe a function to the delegate. This is done with an assignment statement. Notice that we have not included the parathesis after the name of the function! We are assigning the function NOT calling the function.

It’s weird. I know.

The last step is to invoke the delegate. This line also checks if there are any subscribers (actually it’s a null check) - this is done by the question mark. If a delegate is invoked and there are no subscribers an error will get thrown - which is why we need to check before invoking.

Now to be clear. This is a simple implementation. Not necessarily how it should be done, but I want to walk through delegates step by step and not jump straight into the shortest but most abstract syntax.

More On Delegates

Examples of return values and input parameters

Examples of return values and input parameters

Delegates can have multiple input parameters and can even have a return value - or both. It’s important to note that any function that is subscribed to a delegate must have the same input parameters and return value in order to not throw an error.

The input parameters are a great way to send information to other objects. For example when a critter dies it might want to send a reference to itself so that systems know which critter died. That’s not needed in this example, but can be useful in plenty of other cases.

Subscribing and Unsusbscribing of two funtions

Subscribing and Unsusbscribing of two funtions

In general return values are not used. This comes from the fact that delegates are multicast and can call multiple functions which could mean multiple return values. However, only the return value of the last called function will be returned, which can cause all kinds of confusion as it’s not easy or even always possible to control the order that functions are subscribed.

One than one function can be added to a delegate by using the += operator with each function. This operator adds a particular function to the delegate and likewise the -= operator will remove a particular function from the delegate. In general, it’s a good practice to do this in the OnEnable and the OnDisable functions. This is particularly important when a delegate is public and functions from other class are subscribing. If a function from a class instance doesn’t unsubscribe and the class instance is destroyed an error will be thrown when the delegate is invoked.

Example of a static instance of a Delegate

Example of a static instance of a Delegate

Also if the assignment operator = is used all other functions will be removed from the delegate, so in general += and -= are the best practice for subscribing and unsubscribing.

As mentioned above delegates can be made public and even static. In general, I have found that public static delegates are the most useful for the observer pattern. If delegates are made public and static they are accessed (and thus subscribed) to just like any other public static property or field.

Events

Great… So what about events?

Example of a Public Static Event - with an error!

Example of a Public Static Event - with an error!

Glad you asked. Events are just delegates. The difference is that when we are creating an “event” we are actually going to create a delegate but with the keyword “event” in front of the delegate. This does is a few very important things.

With a generic public delegate the list of subscribed functions could be overwritten by any class OR that delegate could be invoked by any class. Neither of these are good things - at least in general. Using the “event” keyword prevents these two actions from happening. All that can be done publicly to an event is to add or remove a subscriber - which is much safer!

Beyond that the implementation of an event is identical to a standard delegate! Notice that when the assignment operator is used we get an error.

Actions and Funcs

Static Events With Action.png

Okay, so delegates are awesome. What’s the deal with actions and funcs?

Both of these are objects inherit from delegates. And in reality they are just shortcuts to create a delegate. Actions are delegates that can have input parameters, but do not have a return value. Whereas funcs are delegates that can have input parameters and have a return value - funcs handle “return values” as an out value that is always the last parameter.

So what does this do for us with the observer pattern? Not a ton, but what it does do is reduce the number of lines needed to create an event.

Notice that each event is now defined on a single line. The use of the action has already defined the delegate for us. Notice too that the second event will handle an integer input parameter. This is put in as a generic argument to the action. This input parameter is assigned or determined when the event is invoked. Using actions this way is just a short hand for what we’ve already done above.

Back to the Project

Define and Invoke the event

Define and Invoke the event

If you’re still with me and your brain hasn’t melted let’s apply the Observer pattern to the example project.

For our example all the action happens when the critters die and this of course could and should be expanded to other game mechanics as well. So to keep things simple and keep going with the theme of “de-coulping our code” I’ve created a new script that will invoke an event when the object it’s attached to (a critter) is disabled.

Nothing too fancy. This lack of “fanciness” is no small part of the appeal of the observer pattern.

ScoreDisplay.png

Then we have code on the UI element that is displaying the score. Here, the code subscribes in the OnEnable function and unsubscribes in the OnDisable function. When the event is invoked the “Update Score” method is called.

Then finally we have the code that displays the achievement message. This is very similar in that we subscribe and unsubscribe to the event and call a function when the event is invoked.

AchievementDisplay.png

The observer pattern in C# is basically built-in, but it is super useful all the same. This is one of those patterns that if you aren’t using it you really should be. If it doesn’t make sense, then keep working until it does, because it will make your projects so much easier to maintain, easier to add new features and best of all far less error prone.

And that’s really it.

Object Pooling

***New Object Pooling Post - Click Here or Check the Navigation to the Right***

If you’ve been around game design for very long you’ve likely seen a video or a post on “object pooling.” Despite the amazing performance of the modern PC a game can still start to slow down if objects are constantly being created or destroyed. By constantly, I don’t mean one object per frame. I mean 10 objects, or 100 objects per frame OR 1000 objects once every 5 seconds. Those are scenarios where object pooling can save the player from frustrating lag spikes and help an older machine squeeze out a few more FPS.

The idea of object pooling is clever, but prtettysimple. Rather than constantly creating and destroying objects the idea is to recycle or reuse objects. This is most often done by turning the object on/off or disabling it in some way. In Unity there is still some cost for turning objects on and off, but the cost is far lower than creating and destroying that object.

Before we get into the code there are lots of different “flavors” of object pooling. People have different preferences on how to keep references to objects. Personally, I like to keep a list (or queue) of objects that are not in use and that’s how I’ll be doing it here. Other ways to do this is to keep a list of all objects and search through the list for an object that can be used (often an object that is not active). While for most small game the performance difference isn’t much, but I still like the tidiness of a single collection for objects that are ready to go.

Such a Fancy game! :)

Such a Fancy game! :)

I’m also going to show two ways to create an object pool. The first will be the most usual way or at least the way that I’ve seen done in the past. The second will be more of my own take on the pattern and add more generic functionality. I can imagine there may be some performance hit to the way I’m doing it, but again the tidiness of the solution and ease of use, in my case, more than makes up for it.

For this tutorial, I’ll be using the same project as for the “State Pattern.” Check out the GIF to the right or the earlier post.

Simple Object Pooling

Object Pool Simple.png

In the “simple” object pooling I’ll be using a queue to store references to game objects. These objects can then be retrieved from the queue when needed and returned to the queue when they are no longer needed.

If you haven’t heard of or used a “queue” it’s very much like a list in that it will contain multiple references or values. The biggest difference is a queue is a “first in first out” collection - just like a queue in real life. The first object to be “enqueued” will be the first to be “dequeued.” This makes it easy to get an object from the collection. Whereas with the more standard list we would need to get a reference to the object and then remove the object from the list. A queue does that work for us. If this is new to you make sure to check out “stacks” too which are “first in last out.”

The object pool class has three fields.

The first is the prefab that will be pooled. In my case, since I’m using the same project as for the “State Pattern” I’ll be pooling the “critter” objects.

The second is the queue that will hold references to all the gameObjects and the third is an optional parameter that will “preload” the object pool.

Preloading the pool (in the start function) may or may not be necessary and very much depends on your projects needs. If there will be a sudden and large demand for an object, think bullets in a bullet hell style game, then it might be smart to use the first frame (or several frames) of the game to create a large pool of object. This creates a lag spike at the beginning but avoids it during the game which is when the player is more likely to notice. In the case above, all I’m doing is instaniating copies of the prefab and adding them to the queue.

The object pool class also needs a function to “get” an object as well as “return” an object - both of which will be public. There can be a good argument to make these functions static as well, but I choose to keep things simple.

The “Get Critter” function will first check if there are any critters in the pool and if there are it’ll “dequeue” a critter, set it to active and then return that critter object. Instead, if the pool is empty the function will instantiate a new instance and return that object. Creating a new object is not always necessary or might not even be a good idea depending on your design constraints. In my case I’m happy to create as many critters as necessary. Another option would be to create a limit on the number that can be created - this could help control an unforeseen edge case.

The “Return Critter” function will be called by the critter itself when it has been disabled. This simply add the critter object back to the queue and then turns the object off. In some cases you may not need to or even want to not turn the object off - it just depends on the use case and the type of object. For my project turning the critter off is easy and I’m not worried about the minor performance hit of turning objects on and off.

Spawning

Simple Spawner.png

For object pooling to work we need a “spawner” object. To serve this purpose I’ve added a small cube with a “spawner class” on it. The class contains a value that controls how frequently an object is spawned, a values that tracks how long since the last object was spawned and a reference to the object pool.

In the start function a reference to the object pool is cached.

Then in the update fucntion the time since spawn is updated with the time of the last frame. This creates a basic timer.

Then if the time since the last spawn is greater than the spawn time - we get a new critter from the object pool. It’s important when using object pooling to be able to “initalize” the objects. In this case that means moving it to the correct position, but for more complicated objects you may need to create a dedicated initialize function. Lastly, we set the time since spawn to zero so the timer restarts - without this the spawner would create a new critter every frame!

Critter Return Simple.png

The last piece of any object pooling system is returning the object to the pool. There are many ways to do this, but for simplicity I’ve created a new class that needs to be added to the critter. This class when disabled will return the critter to the object pool. This works, because when the NPC attacks the critter it calls a function that turns off the object.

Now this is all pretty good and not too complicated to implement.

BUT!

There is a glaring problem, at least in my eyes. When a project gets bigger and more complex their will be a need for more and more object pools.

Each. And. Every. Object will need it’s own pool. Yikes. That gets to be a mess in a hurry. And that’s where my next approach comes in.

“Advanced” Object Pooling

My personal project is a game that will be 100% okay if it runs at 30 fps or even 20 fps - it hopefully won’t but it would be okay. It also has a lot of objects that need to be created and destroyed. This includes spaceship modules and UI components. There will (hopefully) be 10’s or maybe 100’s of different ship modules. So it’s impractical to create a object pool for each type of object…

“Advanced” object Pool

“Advanced” object Pool

It could be possible to just create one big object pool and then search through it trying to find the object that is currently needed, but I don’t like that approach either.

So my approach is to essentially create a pool of pools AND create pools dynamically at runtime when needed. How’s that sound?

The basic functionality is pretty similar to the earlier example in that we are getting and returning objects, but in this case I’ve created a dictionary that uses a string as a key and a queue of game objects as the values.

For each prefab the name of the prefab will be used as the key and a queue of those objects will be created. The object pool class is no longer specific to a given object and therefore we only need one instance per scene.

In the “Get Object” function we have an incoming prefab that is being requested - this is an important distinction to our previous verison of object pooling. We then check to see if we can find a value in the disctionary that matches the name of the requested prefab. If a value can be found we then check to see if the queue has any entries. If it doesn’t, then we create a new object and return that object. If the queue does contain a game object we “dequeue” it, set it to active and return the game object. Very much like what was done before.

There is one additional case, that of not being able to find a value in the dictionary. If this is true we also create and return a instance of the requested object.

NOTE: In the “create new object” function we are naming the new object the same as the incoming prefab. This is crucial since we are using the name as the key in the dictionary and if we don’t rename the object Unity will add a numerical suffix to the object’s name and will break our system. This is a major point of brittleness in this approach. You could also encode the key in another way such as an enum on a script.

Spawner Class

Spawner Class

The real magic of this system comes in the return function. Here once again we check to see if we can find a matching value in the dictionary. If we can, we simply “enqueue” the object. If we can’t find a value then that means this is the first time this type of object or prefab has been added to the pool. So we need to create a new queue, enqueue the returned object and then add the queue to our dictionary along with the corresponding key.

It’s a bit more abstract, but quite a bit more useful!

Spawner

The spawner in this case is nearly identical to the previous case but with two important differences.

We’ve added a “gameObject” field that contains the prefab that will be spawned. The second important difference is that we are now calling a different function to get an object but more importantly we are also passing in the desired prefab.

Returning the Object

Critter Return Advanced.png

Just like with the earlier example we need to return the object to the pool. And this code is functionally identical to the earlier return class.

Conclusion

This second approach allows us to pool any prefab. All we need to do is give the spawning object a reference to the prefab. In my project this means I can create a “Green Critter” prefab and drop it into a different spawner object and it just works… In my opinion that’s pretty darn slick!


Cheat Codes with Unity and C#

Let’s talk cheat codes. This post, and the video that’ll get made from it, are all about the why and the how of adding cheat codes to your Unity project.

Why Add Cheat Codes?

You can see the code at the top right... If you look closely.

You can see the code at the top right... If you look closely.

Great question! There’s the obvious answer is that they can be fun easter eggs for your players to find and discover. In my first game I placed cheat codes in the wallpapers that players could earn by collecting cards on Steam. I’m not sure anyone found them, but I thought it was a fun idea :)

But that wasn’t the reason I first put cheats into my game. The idea was a suggestion of a twitch viewer (Wago) as a way to help with testing and debugging.

In my game, like so many others, you had to collect resources. Those resources were then used to create things like buildings or catapults. If I wanted to test that my UI was working or the placement of a building was working, I’d have to start the game, create a bunch of workers, wait for them to collect the resource and then I could test the placement of the building.

Now this didn’t take much more than 5 minutes, but when you need to do it 5, 6 or maybe 10 times in a row you end up wasting a lot of time.

And that’s where the cheat codes come in. With a few lines of additional code I could instantly have as much of any resource as I needed. A few keystrokes and the resource was available.

This changed a 5 minute testing cycle into a 30 second testing cycle. Which is HUGE! And I’m willing to bet that your project can benefit from cheat codes too.

Enough Already! How Do We Do it?

Nothing too fancy here.

Nothing too fancy here.

Adding cheat codes is surprisingly easy. Or at least the number of lines of code is pretty reasonable - we’re talking 75ish lines. Most of the code is working with strings which was a bit foreign to me but it’s pretty straightforward.

The way I’m going to do this takes advantage of Unity events and the first thing we need to do is create a custom class that will hold the code itself and the unity event. I’ve made the class serializable so that it will show in the inspector. Also note that the class is not a Monobehavior as we won’t be adding this to a gameObject, but rather we’ll be creating a list of instances of this class.

The “On click” portion contains Unity Events.

The “On click” portion contains Unity Events.

If you’re unfamiliar with Unity Events these are the same things that are in the inspector under “On Click” for a Button component where you can add an object and then call a public function when the button is pressed. They can be really handy and they can used in your own custom classes!

After the class is setup we need to create another class for the “cheat code manager” along with a few variables.

All the variables are private, but once again I’ve serialized them so that they can be seen in the inspector. This will help with debugging and in the case of the list it will help with the creation and assignment of the cheat codes themselves.

CheatCode_Variables.png

The first variable is a simple boolean which essentially tracks whether the player is typing. Which isn’t actually entirely true. Rather the value of the variable is toggled by pressing enter or return. This is how the player or developer will signal that they are entering or are finished entering a code - by pressing enter.

The string variable will simply track the characters that have been typed. This will also be used to compare against cheat codes in the list to determine if the correct code has been entered.

Lastly there’s the list - it’s a list of cheat code (instances) and the related Unity Event that will be called if that code is entered.

The backbone of the code - the Update function!

The backbone of the code - the Update function!

Next up is the core of the code, which is sitting in an Update function. The first step is to check if the enter or return key has been pressed. If this is done while (or after) the player was typing then that indicates that the cheat code is complete and we need to check if it’s correct. We’ll get to the “check cheat” function in just a bit. Try not to get too excited :)

After that we toggle the value of the “player typing” variable to the opposite of its current value.

The next piece is a bit of a mess of if’s and such but hopefully isn’t too tough to follow.

If the player is typing then we need to process the characters that they’ve been typing.

To do this I’m using a foreach loop that will loop through all the characters in the current input string. The value “Input.inputString” tracks all of the keys pressed in a given frame. While it’s unlikely that you can type so fast as to get multiple characters in a single frame it seems reasonable to cover all the cases.

So first we need to check if the backspace or delete (Mac, right?) keys have been pressed. If either was and the current string is longer than 0 characters we’re going to remove the last character in the string. This is done with the “substring” function. Which will essentially make a smaller string out of our “current string". We have to give the function a starting index, in this case the 0th character and and ending index, in this class the length of the string minus 1 so that we remove just the last character.

The next “if” checks whether the enter or return key was pressed. If this happened then we’ll reset the string back to an empty string.

Now you might be thinking that it might makes sense to put this further up in the update function when we were checking for the return being pressed.

But!

There is a subtle and important reason not to do that.

The enter and return keys are also recorded as characters with “Input.inputstring” and we don’t want those recorded in our current string as it will mess up the cheat code! So we need a way to filter them out - which is one of the purposes of this “else if” statement.

And lastly, the final conditional is going to add the character to the current string so we keep it updated and will be able to compare it to the cheat codes.

CheckCheat_Function.png

The last chunk of the C# code is the “check cheat” function.

This function is pretty straight forward. It takes in a string parameter, then loops through all the cheat codes in the cheat code list and checks if the input string matches the cheat code string.

If it does, the event on the cheat code instance is invoked and we return a true value.

Otherwise, if the loop finishes without finding a match a value of false is returned. The boolean return value for the function is totally optional, but could serve a purpose in some projects or applications.

The State Pattern

Whoa. It’s been nearly a year since I’ve made a post. I’ve been busy. A lot has happened, but that’s a topic for another post.

So I’m going to try something new, well a few things. But the first thing I’m going to try is writing a blog post for my next video. I figure taking the time to explain the video in writing will help me cement the ideas and provide one more resource for you all. There are many people who’d prefer to read than to watch a video. So maybe it’s a win-win? We’ll see.

But enough of that. Let’s get onto the second new thing.

That’s is exploring programming patterns. It’s something I’ve wanted to do because I want to learn more about programming patterns. Plus Bolt 2 will eventually (!!) get released and when it does many of the basic programming patterns will be far easier to implement AND folks developing with Bolt can benefit from implementing them.

Since Bolt 2 is now fully in hiding under the protection of Unity (who knows when the alpha will make it out to the public again) the upcoming video will be entirely C# based.

I should also give credit where it’s due. I’m no genius - that should be clear if you’ve read more than a few paragraphs of my writing. Much of what I know or think I know about programming patters comes from the book “Game Programming Patterns” by Robert Nystrom. It’s well worth a look if you are unfamiliar with the topic of programming patterns..

The State Pattern

“Allow an object to alter its behavior when its internal state changes. The object will appear to change its state.”

Like any other pattern the State pattern has its limitations, but also like any other pattern when used correctly it can help to detangle code which can make debugging code or adding features easier and much less frustrating. And that’s a win no matter how you look at it.

You may have heard the term “Finite State Machine” or “FSM” thrown around. Both of these terms refer to the same thing which is an implementation of the state pattern. The Unity asset Playmaker is based on the uses of FSMs and Bolt has the ability to create them with “State Macros.”

To help illustrate the state pattern, I’ve created a simple Unity project. There is a NPC played by a capsule and it’s goal is to wander around the maze and collect the yellow cubes. When it sees a red sphere (critter) it will chase it and attack it. Nothing too fancy.

So with that in mind, how would you program this behavior? Take a minute and think it through. No cheating!

Just about ready to go up on steam! ;)

Just about ready to go up on steam! ;)

This actually doesn’t look too bade with the use of functions… but will get out of control in a hurry.

This actually doesn’t look too bade with the use of functions… but will get out of control in a hurry.

I know when I first got started with C# and Unity, I would have done it with an if statement or two (or seven). And that works. It really does. Until you need to add another behavior. Or another game mechanic gets layered in. And we all know it won’t end there. The layers will continue to get added until the code breaks, bugs appear or the project gets forgotten because it was getting too hard to work with.

Simple FSM = Enum + Switch

So let’s look at the simple FSM. I still remember learning about this and was utterly confused by how to implement it but at the same time amazed at what it did to my code once I finally got it working. At that time I hadn’t really learned to use functions well so I had 100’s of lines in my update function. Needless to say it was nearly impossible to debug and when I discovered FSMs it was a major break through!

Simple FSM using an ENum and a Switch

Simple FSM using an ENum and a Switch

In the case I described above the NPC behavior can be broken down into 3 different states or 3 different smaller behaviors. I thought of these as wander, collect and attack. A custom enum can then be created with these three values.

With the enum created a switch statement can be placed in the update function. For each case we can call the relevant function for that behavior. But we still need a way to change or switch (get it!) the state. For the most part this can still be done with basic if statements.

And now this may sound like we’ve back pedaled to our original solution and just made things more complex.

But!

There is a major advantage here!

When we started, inside the update function we had to have a way to determine which state we were in - picking from ALL the possible states. Imagine how complicated that would be if there were 5, 6 or maybe even 10 different states. Yuck! Nothing clean about that.

With this method we only have to decide IF we need to change states GIVEN that we are already in a particular state. This greatly simplifies the decision making albeit at the cost of a few extra lines of code.

In a FSM it’s common that a given state can only transition to a limited number of other states. For example in my case maybe I don’t want the NPC to stop collecting if it sees a red sphere and it should only attack a sphere if it’s wandering around with no cubes in sight. If that’s the case the “state pattern” may actually reduce the amount of code needed as well as serving to untangle the code.

This implementation of the state pattern can be used for all kinds of different behaviors. It could be used to control animations, background music, or which UI elements are being displayed. 

As an aside, in my personal project, I use a vaguely similar approach that makes use of a static enum and events for game modes so that various managers and UI elements can act or react based on the state of the game. The clarity of being in exactly one state has greatly simplified my code and made it far less error prone.

So this is all well and good, but you may be able to see the end result of this approach is still messy if the number of states starts to get large.

A Step Further => More Abstract + More Manageable

Having all the states switching inside the Update function can quickly get unmanagable and if nothing else is pretty hard to look at.

So let’s go one step further. This step adds another layer or two of abstraction to the system, still has some downsides but does clean up our code and will make larger FSMs easier to manage.

This step will place each state in its own (mostly) self contained class. The state will be in control of itself and will determine when to make a transition as well as determine which state to transition to.

Interface.png

Step 1 is to create a new interface. In my case I’ll call the interface INPCState. The interface will have just one function that will take in all the NPC data and will return a value of the type INPCState. This returned state will be the state for the next frame as the “Do Action” function will be called by the base class of the NPC which in turn will run the behavior for a given state.

The Wander State with all the functions included

The Wander State with all the functions included

Step 2 is to create a new class for each state of the FSM and that state needs to implement the interface INPCState. Each of these classes should also contain any functions or logic needed for that state. In my case I have choosen to leave all the variables on the NPC base class. This keeps each state class tidy, but does mean that the state class will be changing values on the NPC base class which is usually something I like to avoid - you win some and you lose some.

Inside each state’s “Do Action” function we need to call the relevant functions AND we need to decide which state to use for the next frame. You can see the full code to the left, but for now let’s jump back to the NPC base class which will help make sense of the return values.

Step 3 is to refactor the NPC base class. Here we need a new variable of the type INPCState that will hold a reference to the current state. We also need instances of each state - it would be possible to make this work with static classes and using an abstract class rather than an interface, but if you know what that means you can probably implement it yourself.

The simplified NPC Base Class

The simplified NPC Base Class

In the OnEnable function I’ve set the current state to the wander state to ensure that the current state variable is never null.

Then the real magic happens in the Update function. Here we have just one line! So awesome. Here we call the “do action” function on the current state and then set the current state to the value returned from that state.

That makes total sense, I swear it does, but it’s abstract.

Give a mintue to let it sink in.

This is so clean.

Step 4 is to add conditionals to the state classes to determine which state to be in for the next frame. Notice that we have passed in a reference to the NPC base class into the “Do Action” function and from there we can get a reference to the instances of the state classes.

Pro’s

The base class is exceptionally clean. You can now see how the class appears to change it’s state (behavior). Effectively the entire Update function changes depending on the current state and what in that state’s “Do Action” function. That’s cool.

If we want to add an additional state we simply create a new class, add an instance to the NPC base class and finally add conditions to allow a transition to the new state from other states.

As long as the number of states stays fairly small 5 or maybe 10 this is a pretty manageable solution.

Con’s

It’s hard to maintain if the system truly gets complex. In this case most sophicated structures such as behavior trees might be needed.

All the variables in the NPC base class are public. Which is a bit messy and not super awesome. This could be partially solved by creating a data container that itself is private in the NPC base class but has public variables… This passes the buck a bit, but would prevent those variable from being changed by classes without access to the data container. A generic data container would also potentially open the doors a bit wider for reuse of the states by other NPC types - so worth thinking about.

As mentioned before, the states are changing values of variables on the NPC base class. Not ideal and something I usually go out of my way to avoid if possible.