explosion-01

Chemical Chaos ~ Ludum Dare 37 (One Room)

It’s been over a week since the last Ludum Dare competition ended. This time round, the theme was ‘One Room’, so naturally I made a game about a bunch of chemistry experiments that you have to run around and keep going. This decision was somewhat motivated by the fact that everyone I’ve ever talked to loved chemistry at school and would do anything to do a titration again. After all, knowing your market is half of the battle in game development.

The idea I was going for was a game where the player would be constantly running around, getting one experiment in working order, to find that another couple are starting to fail. It’d ideally be a very hectic game made up of several really easy minigames. For maximum effect, I’d need to create quite a few different experiments; however, I only had enough time to make three to a decent level of completion. I’d also have liked more time to polish some of the game’s aspects, mainly some smaller details like particle effects and other signposting to make it easier to see the status of experiments from afar.

ld37-01

Don’t ask why it turns from blue to red.

The first experiment was a distillation – in real life, you do this experiment to separate some liquid from a solution (you probably used it to purify water in school). The controls are simple – just mash the mouse buttons or controller shoulder buttons to turn down the temperature, as shown by the thermometer. When this experiment fails – when the thermometer is full – there’s a large explosion for no apparent reason.

explosion-01

The most important part of development – particle effects.

There’s a couple things I’d like to improve about this minigame. First of all, the apparatus should probably start to smoke and rattle around a bit as it’s getting close to exploding. And on the subject of explosions, I think the explosion needs to have more impact – sure, all the equipment goes flying and there’s a bit of fire, but I might add more flames that stay alight for a while on the table, and possibly violent screenshake when the explosion actually happens. On the plus side, I was very happy with the ‘reaction cam’ that pops up in the corner when an experiment fails.

ld37-02

John is the best video game character this year.

The second experiment was the good old sodium-in-water one, which as we all know, causes fire. The gameplay for this one involves pressing left click/LB to decrease the amount of sodium and potassium that materialises above John, the water tank, and right click/RB to spawn more. If he gets too little metal, he’ll get bored and will fall to sleep and if he gets too much, he’ll get scared then eventually die. Please try not to kill John.

There are a couple of problems in this screenshot – first of all, the sodium blocks sort of clip through the bottom of John instead of bursting into flames on the surface of the water, something I didn’t catch happening before submission. I’m also confused what may have caused it as I touched none of the relevant code for this between getting the feature working and submission. Secondly, the instructions for this experiment are incorrect, as I seem to have put up the instructions for experiment 1 instead; this was probably just an oversight. They’re both easy-to-fix problems, but they could have easily been avoided.

ld37-03

I’ve left my mixtape in all three of these Bunsen burners.

The third and final experiment is the Flame Test, which tasks you with carrying different elements into three flames. Each flame expects the element that makes it burn in a particular colour, as dictated by the chart next to the Bunsen burners and the base of each burner. All other elements go in the bin; if you’re too slow trashing elements, you’ll fail the game, and if you put the incorrect element in a flame, that flame will go out and losing all flames results in failure too.

In hindsight, I should have made the Bunsen burners explode when you get things wrong. It’s basically the only thing wrong with this minigame.

ld37-04

For the flame test minigame, I invented new elements so I could make more interesting flame colours. There’s a line of posters along the wall with short descriptions of them all. Given how long it took me to think up the new element types and make posters and models for each of them, I would have liked to make more games that utilise them all, but unfortunately I didn’t have enough time. One game idea I had was a solution-mixing table, which had a bunch of coloured solutions and you had to make the requested colour. However, it’s not really an experiment that’s easy to make hectic and if you’ve ever dealt with transition metal ions yourself, you’d know that this type of colour change chemistry can be a little complex. For the two people that got that tortured chemistry pun, I’ll see myself out.

I was, however, pleased with how the game came out graphically. The only issue I had was trying to make a roof and windows; doing that messed up the lighting, and any amount of time trying to work out Unity’s area lights and baked global illumination seemed to be wasted in the end.

You can give the game a go by visiting the Ludum Dare page, where you can vote if you took part in the competition, or directly on my Google Drive.

ghosts_header

Ghost Party ~ WGD ‘Spooky (2016)’ Three-Week Competition

It’s been a while since I’ve properly sat down and made a game, apart from the Zero Hour Game Jam, which I entered with an entirely broken game about shooting ghosts with a flashlight. Today, after having three weeks to work on a game, I decided to start one the day it was due to be shown.

3dspooky5me

My Zero Hour Game Jam entry, the lesser of my two games about flashing ghosts.

I decided that my Zero Hour Game Jam entry had a few flaws, the main one being that you magically die after about 30 seconds every time without being visibly hit by anything. You hit ghosts by aiming straight at them; unfortunately, this means you have to aim the centre of the screen at them as the game uses a raycast, but there is no crosshair so it’s almost impossible to tell if you’re hitting the mark except that the ghosts turn red.

I did like the idea of hitting ghosts with a flashlight though, so I kept it and made a brand new game today with a different art style: crayons. You might think I’m crazy, but when you’re time-constrained, it always helps to think of quick hacks to make things easy. I could have just as easily used normal coloured pencil to draw everything, but a bad artist (or in this case, a rushed one, although I’m not exactly Picasso to start with) will always make coloured pencil look crap. On the contrary, when someone thinks of wax crayons, you think of a 5-year-old’s drawing tacked onto the fridge. Essentially, wax crayons have a very low skill ceiling and I exploited the heck out of that. It made for a very consistent style and I actually really like it! It’s similar to the style I used for Tappy Dev, but I think it’s possibly better.

screenshot_01

Yellow ghost is far too happy.

The general idea is that ghosts spawn from left and right, and it’s your job to shoot them down with your flashlight by clicking on them. It’s better than 3DSpooky5Me (my 0h game jam game), in that you can see the mouse cursor to indicate where you’re aiming. The ghosts are also much cuter.

Given more time, I’d go back and make sure the proportions of all the objects in the game were consistent. As you can see, the ground’s outline is very thick compared to that of the ghosts, despite being drawn using the same crayons. I’d also change the design of the gravestones and the large tombstones, since my friend said they look like printers. While the thought of a haunted Konica Minolta fills me with glee, I might save that idea for when I’m in a real jam.

I also need to change the mechanics a bit. Similar to the 0h Game Jam, I didn’t make the flashlight affect an area, but stuck with a raycast; having the flashlight hit all ghosts in its range when flashed would open up the possibility of combos and make the mechanic feel more satisfying when you line up 5 ghosts in the same flash. Currently, the score increments by a strange formula I devised based on the speed, sine-waviness and z-distance of the ghosts, but I feel this should be better communicated to the player, as it’s difficult to even notice how many points you got for hitting one. Furthermore, one thing the game lacks entirely is a lose condition, which I was minutes away from getting in the game, but was hindered at the last moment by having to go to the WGD event in which I showed the game.

But the biggest and funniest problem in this build is the unintentional and bewilderingly fast escalation in difficulty. Above was a screenshot from about 30 seconds in, but the following one is from a couple minutes in:

screenshot_02

Points for spotting the cameo appearance.

At the start, the difficulty increases in a linear fashion. Every 5 seconds (although I’d planned to change it to every 20 or 30 seconds and forgot), the time interval between ghost spawns goes down by a fixed amount. It does this 10 times, then it starts going down in a geometric progression. You can see where this is going. Every 5 seconds, the time between spawns is divided by 1.2. Then you end up with a ghost party. It’s a classic example of “oh I’m sure this arbitrarily-picked number will be fine”.

At the early stages of development (read: while zoning out in a lecture this morning, thinking about spooky ghosts), I considered adding some element of a rhythm game into this, but as you’ll find out there is no sound whatsoever. It’s somewhat inspired by the Sneaky Spirits game from Rhythm Paradise (or Rhythm Heaven, for you Americans). I wanted each ghost type to have their own behaviour, but this didn’t come to fruition and they instead all follow sine waves of varying frequency and magnitude.

I wanted the spiky green ones to zig-zag, the puffy white ones to flutter upwards and fall back down a bit constantly, and the blue ones were going to have Pacman-style grid movement. The pale ones were going to have an animated tail that wiggled around and the rare Drifloon (please don’t sue me, Nintendo) would’ve occasionally grabbed a headstone with its tassels and flown off with it. Maybe next build!

All things considered, the most important lesson I’ve learned today is that I should drawn with crayons more often. It’s really easy and looks pretty nice, especially with the Paper Mario-style aesthetic. It’s also not really apt to keep referencing ‘today’, but I’m not a clock so it’s fine. You can download the game here.

ld35_u1_game_banner

Shifting Dungeons ~ Post-LD35 Update 1

One thing I’ve become exceedingly bad at is updating games once I’ve thrown them onto the Internet for the first time. The last time I did such a thing was probably over a year ago. But, starting today, I am a changed man! For I have vowed to complete Shifting Dungeons to a standard that I’m happy to put my name to and watch it run off into the wider world, playable and somewhat consistent. Ahh, games, they grow up so fast. I’ve been very preoccupied lately with ruining my sleep schedule by doing coursework right up until deadlines (and beyond…), but that didn’t stop me tweaking Shifting Dungeons a bit.

Without further ado, it’s time to list what’s changed! That’s what change-lists are for, after all.

giphy

Character Customisation

There’s a handful of new character customisation options, bringing the total of skin and clothing colours available to 8 each. That may increase in the future, but for now I’ve stuck with 16 total options because the UI feels clean and not overwhelming with choice, while providing a relatively broad number of outfit combinations.
The whole character customisation scene has a background too – I’ve decided to make it look like the player is getting changed in their bedroom. It’s woefully incomplete currently, but it’s a start.

promo-dev-06

Options Menu

The bare basics of an options menu are also now in the game. Most importantly, this menu has an exit button – something I’m very good at forgetting to add. Now you don’t have to Alt+F4 out of the game or use Task Manager! There are sliders for adjusting music and SFX volume and for changing text speed, but they don’t do anything right now (especially since there’s no music and next to no text). However, the sliders’ values are accurately stored, so it’s a start! I’ll probably have them fully implemented by next update.

promo-dev-04

Intro Cutscene

I’ve also started work on a cutscene for the start of the game. It’ll be rather short and serve only to introduce the concepts and backstory of the game in a better way than the Ludum Dare entry version handled it – a wall of text. Instead, short sentences accompanied by pretty pixel art will probably work better. Similar cutscenes will appear during major story arcs, but since there’s no story right now, this is the only cutscene implemented.

promo-dev-05

Controller Support

Any controller that supports X-Input should work with the game. I say should; I’ve been testing the game using a Wii U pro controller and an adapter that allows it to mimic an Xbox 360 controller (which uses X-Input), so hopefully it also works with other X-Input devices, although I can’t promise anything will work perfectly. The controls are fairly simple and you shouldn’t have any trouble getting to grips with them. However, there are no in-game instructions for controllers, so here is an image detailing how the controls work (which I probably could have just included in the game anyway):

promo-dev-02

Enemy Lock-on

To make it easier to take down baddies, you can now lock onto them. On a controller, aim in the general direction of the enemy and press the left button; using a mouse, press the right mouse button. It’s the same button to de-lock (lock off?), but make sure you’re not aiming at an enemy when you do it or it’ll just lock onto the new enemy. Unless that’s what you wanted to do, then great, that’s how you do that. When locked onto an enemy, their health will appear next to them and decrease in realtime, plus your bullets will fire straight at them, so you can see why it’s a handy feature. Plus, when you kill a locked-on enemy, it’ll automatically lock onto any nearby enemies. To aid your aiming, there’s a second cursor – the orange one is for locking on while the white one is the mouse’s actual position. I’ve yet to implement the white cursor for controller input, but it’ll be in the next update for sure. Oh, and the cursor sprite and animation is a lot fancier, too.

promo-dev-03

Mechanical Changes

The biggest gameplay change is possibly the addition of the Energy bar. There is a distinction between powerup energy and general energy, hence there two energy bars; the leftmost one, with the thunderbolt icon, will decrease when you fire bullets or slow down time and replenish when you move. The one on the right, with the arrow icon, starts off full when you pick up a powerup (try saying that five times fast), then slowly falls as you move until it reaches zero and the powerup expires. Health replenishes as you move as before, but at a slower rate, plus the UI is more reactive; being hit makes the health bar shake, and having low energy makes the energy bar shake more, the lower energy you have. Staying stationary also no longer stops time completely, but it slows it down a lot.

Shooting mechanics have had a bit of a mix-up too. Your bullets and enemy bullets don’t collide any more, as it provided an easy way to get rid of enemy attacks and there was no incentive to use the time-slowing mechanic to dodge bullets. However, you can now hold down the shoot button to start a hailstorm of bullets and wipe enemies off the map without me being liable for loads of repetitive strain injury lawsuits! To balance the increased shooting speed and the ability to lock on to enemies, your bullets do half as much damage, although in the next update I hope to add some system such as different bullet types that’ll let the player (and enemies) do more damage.

A few other changes are there, namely that rooms are much larger and the camera is zoomed out so the player can see further. It makes it slightly less confusing when you can hear you’re being shot at, since you can more easily see where it’s coming from by virtue of the threat actually being on-screen or only just off-screen, not a million miles away.

giphy1

Yay low-quality GIFs! My computer is just bad at everything…

Bug Fixes

You know that game-breaking bug I wrote about in the last blog post? The one that means you couldn’t get past the first dungeon because you’re unable to move on its final floor? That’s been squished. There were also a couple oversights where the game would sometimes skip to the final floor when there was supposed to be another standard floor before it, but now the floors act like they should.

Bugs Implemented

There’s only one that I’ve actually found and can remember, and it’s not hugely important: on the character select screen, the player’s face appears blank. That’s because technically he’s looking upwards, and due the the fact the player’s at an angle in 3D space, the game doesn’t recognise the mouse position correctly and doesn’t face it. If you press the right stick on a controller, the player will face the correct way, but unfortunately the right stick’s rest position has the player looking upwards anyway… Swings and roundabouts, huh?

promo-dev-07

Meet the very introverted and shy hero of the game.

Next Update’s Priorities

Most of all, I hope to implement more enemy types. Right now, there’s only one type, and they share the same sprites as one of the character customisation options. They all share the same terrible AI too, so I’m going to at least attempt to work on pathfinding and give some enemies different attacking styles. I’ll also try to make more dungeon types and give more variety to the dungeons themselves – different sizes, shapes and maybe obstacles inside the rooms. Plus, I’ll try to finish the powerups that were originally planned for the Ludum Dare version and implement new ones – the ‘shapeshifting’ aspect of the game is a little bare currently. Finally, I still need to balance the floors’ difficulties and spawning rates of enemies and powerups, since it’s still very imbalanced.

ld35_u1_download_banner

ld35_game_banner

Shifting Dungeons ~ Ludum Dare 35 (Shapeshift)

This weekend was the thrice-annual Ludum Dare game jam. The rules for the competition are simple: working alone, you must create all game assets yourself and come up with a complete game in 48 hours to abide by a predetermined theme. There’s also a more relaxed ‘jam’ version, with a 72-hour time limit, in which you may work in teams and use assets from online, but because I must be a masochist I entered the competition version for the fifth time in a row. These game jams are a bit of a habit now!

The theme is voted on by the community beforehand in several phases (and is almost always terrible), so this time we got stuck with ‘Shapeshift’. Immediately the idea of shape-shifting dungeons came into my head, because I’ve been hanging out with people obsessed with making Mystery Dungeon-like games for far too long (James, I blame you. Unless you’re a different James, then carry on with your day). I’ve basically made a dungeon crawler-meets-my Ludum Dare 32 entry, but it has a twist!

press-02

I tried making the art look pretty. I think it worked?

In some tile-based dungeon crawlers, such as Pokemon Mystery Dungeon, players and enemies move simultaneously each turn. However, to avoid having to create a tile-based turn system, I’ve allowed players and enemies full 360-degree movement. To keep things somewhat ‘simultaneous’, enemy and bullet speeds are tied to the player speed. Think 2D SUPERHOT. This allows the player to stop for a moment and think: do I shoot the enemy’s bullet down before it hits me, or move to the side and shoot them directly? It’s the closest analogue to a turn system I could think of in a continuous game other than each character moving in turns of, say, five seconds each. Which would have sucked.

press-03

I also added a couple of powerups for the player, and had planned more that got cut due to time constraints. Currently, there’s the axe powerup, which turns the player into a massive slab of metal on a stick that ups attacking power massively and increases defense. There’s also a slime powerup that turns you into an amorphous blob (in the style of Dragon Quest’s slimes) and lets you shoot bullets that slow enemies (or, well, they would if they weren’t bugged in the release version). That brings me to the next feature: bugs!

promo-post-01

The second dungeon, Glacial Rift. Shame that a bug prevented reaching it.

In the release version of the game, there were three dungeons. However, because of a wonderful bug on the lowest floor of the first dungeon, you can’t access the other two – the player won’t move once you reach that floor. It’s a bug that took 5 seconds to find, one line to correct and was stupidly introduced right before submission – I immediately knew what I did wrong but hadn’t thought to check whether the stuff I added would have any negative consequences. In short, I’m an idiot when I’m sleep-deprived. Above is a screenshot from the second dungeon, Glacial Rift, albeit taken after submission (I’ve been working on the game a bit since the deadline). There are a few smaller bugs related to combat, but they’ve mostly been figured out and weren’t too disastrous.

press-01

The character select screen was one of the first things I fully implemented.

I had to abandon a couple of planned features, too. Originally, there were set to be more powerups – the Drill, American Footballer and Super Magician. The drill powerup would have let you tunnel through walls, while the footballer would have granted you a powerful charge attack that lets you vault through enemies at high speed. Transforming into the super magician would have given you a cape and made your magic attacks stronger, faster and larger. I also didn’t get time to implement all the little flourishes I wished to put into the game – there are no particles (a disgrace, I know!) or death animations for either the player or enemies. The screenshake is also a bit weak in places – I’ll probably increase the strength when enemies die. On the graphical side, I wanted to have a few more character customisation options, but at least that system was working entirely. I’d also planned a couple more varieties of dungeon theme, like City, Forest or Volcano, but I’m happy with the two that made it through (Temple and Ice).

I’ve already got a ton of notes written down for how I’d improve this game, and that’s just what I’m in the process of doing. I’ll have an updated version up soon! In the meantime, you can play the game on the Ludum Dare website! Just clicky da box below. Voting is still taking place, so if you also made a game for Ludum Dare 35, I’d really appreciate it if you voted for my game and left feedback!

ld35_download_banner

tappy_dev_header_banner

Tappy Dev ~ WGD ‘Fuck This’ 48-Hour Jam

Well this post is certainly overdue. This jam happened from the 26-28th February, so my apologies for taking quite so long writing this one up; the end of term was, as always, filled to the brim with horrible, terrible coursework.

The idea behind the ‘Fuck This’ jam is that participants make a game in a tool, language or engine that they’ve never used or hate using, or that they make a game in a genre they don’t like. That way, you can learn a new skill or add your own spin to a genre that’s never been tried before. Since learning a new tool would’ve taken too long, I opted for a bad genre. That genre was idle games. Since I’ve never really focused much on mobile development, I made Android my sole target platform. Sorry iPhone people and Windows Phone fans (both of you), but I didn’t have either of those at hand for testing.

My idea for a terrible idle game was a game in which you tap the screen in order to make games. Every time you tap the screen, you get a point, and every 1000 points will ‘make a game’. Those games are all jokes or tropes on the games industry, as seen in the example below.

Screenshot_20160324-191950

The counter gets incremented once every time you tap on the screen. That counts for multiple taps at the same time, so the pro strats for getting as many points as possible are to just mash the screen with your fingertips. Not sure if that counts as mashing, but I don’t care, just do it. Gotta get 1000 points to see my hilarious references, after all.

The art style was literally just me drawing badly on some paper using some coloured pencils. I made sure I coloured out of the lines, for good measure. I did this mostly because it was something different from pixel art, but it was also something I knew I could quickly and easily draw. Personally, I think it worked out remarkably well, considering the fact I didn’t spend all that long on it.

As you tap (or, well, ‘type’), the on-screen screen will fill up with text. It’s nothing special, just a measure of progress. And also an insult!

Screenshot_20160325-134436

If you want to try it out, you’ll need to find some way of installing non-Play Store apps on your phone. I’ve also built the game for Android 5.0+, so it (probably) won’t work on versions lower than that. I hope it works on your phone! Just click the banner below to download the game.

tappy_dev_header.png

ggj16_blog_header

Ritual Quest ~ Global Game Jam 2016 (Ritual)

Each year, a game jam is held. A jam that spreads its influence across the world, transcends language and culture barriers, and bands developers from every corner of the globe together to work toward a common goal – making a badass game. That jam is Global Game Jam. And of course, like a gamedev-mad lunatic, I took part.

 

Global Game Jam, like Ludum Dare, takes place over 48 hours. However, unlike LD, GGJ is entirely for fun – there are no ratings and no winners, and instead it’s up to you to make what you want of the event. GGJ takes place across many physical jam sites across the world; jammers must join up to a site and physically be there, or else they can’t receive the theme – this helps foster a ‘community’ feeling and entices people to work in teams. I worked alone, but I had plenty of other people in the room to bounce ideas off and have fun with; it was fun seeing what ideas others in the room were coming up with.

The theme for this year’s competition was ‘Ritual’, which was revealed in the keynote video above. The Warwick University site didn’t get the theme for about 45 minutes because we are definitely very competent, then I spent the next hour or so brainstorming/panicking, until I settled on my final idea – Doodle God meets exploration elements.

Roughly what my ideas were for the original world map.

My idea was that you start off in a grand temple with only Fire, Earth, Water and Air to start off with. By combining pairs of these elements, you must create brand new ones, building up a table of elements. Once you’ve crafted a certain item (hint: that item is Life), you’ll gain the ability to walk and can exit the temple. In the overworld, you’ll come across various areas in which an ‘Interact’ prompt appears on the screen – pressing select in these areas will either find a brand new element, one that can’t be crafted normally, or come up with a new prompt telling you that you need a specific item to progress.

An incomplete version of my very convoluted crafting tree.

In all, I managed to get the vast majority of my plans implemented in the time limit. I made space for 100 different elements in the code and UI, sketched about 81 element ideas, and managed to implement 70 for the final version. Similarly with the overworld areas, I’d planned for a ‘Good vs Evil’ thing with the world map – one one end, you have the River blocking off the Forest, which leads to the Hallowed Forest, with stairs up to the Floating Castle, and on the other end you’d have the Blood River, separating the Desert from the Dungeon, and on the other end of the Dungeon would be Hell. I had to cut the Blood River, Castle and Hell, and I made the Dungeon, Forest, Ruins and Hallowed Forest much smaller than I’d intended, but I’d planned the game in such a way that cutting these areas wouldn’t matter too much. I may work on the game further to add cut areas and elements back in, as well as grouping elements together and introducing a Temple in each area for crafting specific elements.

Given a bit more time, I’d have loved to work on the UI too. In the end, all of the UI elements were just default Unity UI panels and scroll bars, recoloured to make it easier to see when things were selected. I would also give a lot more attention to making the world feel alive; the river is static, there’s no dust blowing in the desert and grass doesn’t sway in the wind, but changing all of that would make the overworld more lively.

ggj16_finished_02

The crafting UI.

I’d also change a few of the recipes. Stuff like “Life + Stone = Egg” feel very contrived and don’t make much sense, even though Doodle God has similar silly recipes; given the time constraint I pretty much went with the first thing that came to my sleep-deprived head. With a little more time to think, I’m sure I can make many of the recipes better and provide alternative recipes for any one item.

Global Game Jam doesn’t have a rating system or a leaderboard of any kind, but I’d love for you to try it out. The version on the GGJ website has a couple of design flaws – you can walk over the River and you must click the mouse to interact with stuff – but the version on my Google Drive, linked on the image below, has fixed both of these issues. Let me know what you think!

ggj16_blog_download_bar

tip_header_14

Game Design Tips #14 – [Unity + C#] Persistent Data

Today I’m gonna talk about how you can save data to disk and read it back later. Unity has a utility built-in for this – they’re called PlayerPrefs – but for anything more than perhaps options and preferences, you’re going to want a more robust system for saving data between scenes within your game or separate game sessions. This is where I jump in and throw a bunch of fancy C# things at you! Note – this system should work on standalone platforms such as Windows, Mac and Linux and mobile platforms, but it won’t work on Web Player builds or platforms such as Samsung TV. I’m not sure if it works on console platforms since I don’t have the resources to develop for any of them and the internet has been unhelpful in this regard, but oh well. Time to get started!

There is a lot of motivation for wanting to save data to disk; high scores, player progress, and player-customised assets are all types of data we want to make persistent. I’ll be showing you how to achieve this in Unity using C#. To do this, we need to package up the data we’re going to save into its own class.

tip_14-01

We’re going to put this portion of code right below the SaveStuff script, which we’ll be writing next. For the SavableObject class, we’ve made a bunch of variables that we want saving to disk. In this example, imagine there’s a guy named Bob, and that he wants to remember his own name, how many bananas he’s holding, how long he’s been dancing (measured in hours – he’s an active bloke) and whether he’s made of wood. From this, we can only assume the following: he’s forgetful, probably a fan of potassium, potentially flexible, and doesn’t remember if he’s a real boy. But my game doesn’t know that! That’s why I’m going to save all this crucial information to disk.

tip_14-02

THIS is my all-knowing, all-powerful SaveStuff script. Let’s gloss over all the important things this script is doing – I’m sure you’ll be able to fill in the rest. It may get a tad boring, but bear with me, because saving things is actually really fun. Honest.

First of all, you can see a small snippet of the SavableObject class at the bottom of the file to show you where I’d place it. It has a [Serializable] attribute (line 36) – in order to use this, we need to import the System namespace (line 2). In the Start() method, we make our new SavableObject and specify Bob’s name as “John” (turns out he’s really forgetful) and his body’s wood status to “true”. The constructor for SavableObject already specified default values for numberOfBananas and danceTimer, so we won’t have to worry about those. Oh, and System.IO is imported for use of FileStream and File, whereas System.Every.Bloody.Word.In.The.English.Language is used for BinaryFormatter. Now let’s save Bob’s status.

Here’s the part where I attempt to make C# exciting! SaveMyStuff() is now going to do a bunch of fabulous things. We make a fun little BinaryFormatter we’ll be using shortly and then create a wonderful, happy file called “myThings.dat”. One thing to note here – I was dumb when writing this example, so it should actually be “/myThings.dat” to ensure the file goes inside the folder at Application.persistentDataPath. We serialise the data from the SavableObject we made earlier (using rainbows), turning it into a binary string that an ordinary user wouldn’t be able to comprehend if they opened the file manually. We then close the file up and wait a second before calling LoadMyStuff() on our loader object (in practice, this second’s worth of waiting may be replaced by an arbitrary amount of time, perhaps even including closing the game and reopening it). Closing the file is a very important step, since C# places a ‘lock’ on the file while it’s being accessed, and trying to access it from elsewhere at the same time – while it’s locked – would be reeeeally bad. Got all that? Good! I told you C# was fun! Now let’s introduce the LoadStuff class and go over its features.

Oh, by the way, Application.persistentDataPath is a ‘default’ filepath that varies by export platform. Most games that use Unity will probably use this default path plus a bit of extra filename appended to it (as I have here). The filepath also contains the company name and game name, both determined in the PlayerSettings in the Editor (found at Edit/Project Settings/Player).

tip_14-03

This script happens to be pretty similar to SaveStuff, but does things backwards. In LoadMyStuff(), which happened to be called by SaveStuff (it doesn’t matter what called this method in practice, I just did that for convenience), I first check if the file “myThings.dat” exist. If it does, I create all the necessary things, as with SaveMyStuff(), but this time I’m opening the file instead of creating it. That’s why it was necessary to check that the file exists, because trying to open it if it didn’t would make things cry/crash/explode. Now that the file’s open, I can deserialise its contents, un-binary format it and stick it back into a SavableObject. Then all there is to do is grab the variables out of that object, plonk them all into a horrible example of how not to concatenate strings together, and watch the Console output all our data with no errors whatsoever.

tip_14-04

Congratulations, you’ve just saved to disk and loaded up that data back from disk! It’s a very useful feature you’ll find yourself using in a variety of places; from remembering player’s preferred options to keeping track of game progress, the possible uses of saving to disk are endless.