A Game Design Tip a Day #9 – [Unity C#] Ditching MonoDevelop for Visual Studio

Unity ships with MonoDevelop, an IDE which does the job fine for the most part. Until it crashes, which is all the time. Or until it runs slowly, which is all the time. Or until it forgets to autocomplete my code, which is all the time. Or until— okay, you get the point, I’m not MonoDevelop’s greatest fan. It’s slow, prone to memory leaks and lacks in features. Plus it’s deleted all of my project’s code on more than one occasion for some inexplicable reason. But it’s fine, because we have a saving grace! Many Unity developers (well, many developers full stop) prefer to use Microsoft Visual Studio. And why wouldn’t they? Microsoft has a solid developer network, very good code documentation and an extremely reliable IDE. Plus they literally invented C#, so there’s that too.

tip_a_day_09
As far as IDEs go, this is the sexiest. Well, maybe after Sublime Text with the Monokai theme.

Visual Studio now has a free Community Edition, so you poor saps out there who don’t have enough dosh for the Professional Edition (or haven’t had it thrown at you by your university) can go grab it for the same price as going outside for some air. Given that you’re looking up game design tips, going outside is probably something you should go do after reading this. We all know that ‘free’ is the best number, so there’s really no excuse to not get it.

The biggest aspect that Visual Studio trumps many MonoDevelop alternatives in is interoperability with Unity’s features. There’s a fantastic plugin called ‘Visual Studio Tools for Unity’ which allows you to debug your Unity project in Visual Studio as easily as you would do using MonoDevelop, plus it has code completion for Unity-specific code that’s better that MonoDevelop (it doesn’t have any more code completion features, it’s just that VS is infinitely faster at it than MD).

One thing that did throw me at the beginning was that Visual Studio very much sits in the “open curly braces on a new line” camp; so much so, that it will try enforcing the practice upon you. To begin with, I was fiercely opposed to this oppressive conduct like a Lincolnshire village opposing a new wind turbine being built within a 10-mile radius, but now I’m kind of glad I went along with it because my code is actually much neater. It’s great if you’re already in the (superior) new-line crew, but it might be strange for you “open curly braces on the same line” slobs.

tip_a_day_09_02
The eternal struggle. Courtesy of Shutterstock and some dodgy GIMP work.

For all you Unity developers, I cannot recommend Visual Studio enough, especially when compared with MonoDevelop. At least Visual Studio has never somehow deleted everything I’ve been working on.

Advertisements

A Game Design Tip a Day #8 – [Unity C#] Coroutines (Part 1)

Unity has a cool feature (I’m not a nerd at all) that lets you run a function over various frames without using some clunky method that’s difficult to write and long as hell. Coroutines are special kinds of method that, together with the yield keyword, can be used to suspend the execution of one call to a function temporarily – this allows it to run over several frames. Well, they’re much more complex than that, but I’ll be going into more detail in another tip at some later date. One great thing about coroutines is that they’re run in the same thread as all your other MonoBehaviour stuff (like Start or Update), so there’s no problems to worry about with regards to messing with the same variable in both Update and a coroutine, for example. They also have minimal overhead while providing huge amounts of functionality.

Coroutines in C# have a return type of IEnumerator:

tip_a_day_08

This coroutine does… absolutely nothing at all, but it’s just here to show you the basic structure of one. Firstly, every coroutine needs a yield statement somewhere in it, or else it will fail to run. In this example, yield return null will cause the coroutine to wait until just after the next Update() method is called. Coroutines also need to be called in a special way – we use the StartCoroutine() method, which has many overloads:

tip_a_day_08_02

The three uses of StartCoroutine in the Start method are all valid ways of calling a coroutine. For coroutines that have more than one parameter, you’ll want to use the third version. There’s also a StopCoroutine(“MyCoroutineName”) method that can be used on any coroutine that was called using one of the string-based StartCoroutine functions, which will tell a coroutine to cease execution forever. Like coroutine murder, with less blood. Unfortunately, that does mean that any coroutines that have more than one parameter can’t be stopped in this way.

There are many other kinds of yield statements you can use, too. Rather than always using yield return null and just waiting for the next Update frame to finish, there’s tons of other yield statements in your coroutine goodie bag:

tip_a_day_08_03

Some of these are very interesting (to reiterate, I’m definitely not a nerd). I’ve listed many of their effects above, and they’re all pretty straightforward. I’ve never really used WWW before, so I can’t claim to know how they work in much detail, but it seems they wait until some WWW download has finished before doing what yield return null does. The next one, yield return StartCoroutine(SomeCoroutine(someParameter)) is an extremely useful coroutine feature that suspends this current coroutine until another one has finished execution. I can even put a similar statement in the second one to wait for a third coroutine – this is called coroutine chaining. Just be careful that you don’t create a circular chain of coroutines that call each other, or things will get very ugly very quickly. You’ll want to be careful when some of these because they run in a specific order – for example, a WaitForSeconds always runs before a WWW. Consult Unity’s Execution Order of Event Functions manual page for more info – the diagram at the bottom of the page should be ingrained in your memory by now.

I’ll be wrapping up some other coroutine features in another tip some day, but for now I’ll leave you guys to play around with these ones.

A Game Design Tip a Day #7 – [Unity C#] Prettier Variables in the Inspector

Spaced Out

When you have a script with tons of different variables, more often than not you’ll just end up with a huge list of variables and it’ll get tedious trying to find the variables you want to change in the Inspector. There’s an easy way to remove this frustration – use the Header and Space attributes.

The ‘Header’ attribute is used to give a subtitle to groups of variables in the Inspector. Its syntax is [Header(name)], where name is a string of your choice which will act as the header. The ‘Space’ attribute can also help with organisation, as it leaves a small gap between variables in the Inspector. It’s used much the same as Header, except it’s given an integer parameter which tells the Inspector how many pixels high the gap should be. The syntax for Space is [Space(height)].

This is what a script looks like in the Inspector without any of these special attributes:

tip_a_day_07
Imagine this list of variables, except too big to fit on a screen. Welcome to Unity.

As you can see, it’s not terribly useful for all these variables to be so close together. It’s far worse when you have about fifty bloody variables with loads of different types and tons of different functions, at which point it becomes impossible to find where you’re supposed to modify values or assign game objects. In this example, it’d look much cleaner if we separated the attack variables from the rest and gave it a header. And that’s just what we’ll do:

tip_a_day_07_02
I’ve always wanted to be able to find variables in the Inspector. I swear, one day I’ll be able to.

This makes things very slightly neater than before. I’ve used Space to separate the ‘script’ parameter from the rest, and a Header to highlight the attack variables more clearly. Header provides a small amount of space on its own, so I didn’t need to worry about leaving a space above the header.

Bounding your variables

In this example, there’s something else we can do to make the designers’ lives easier and make things less likely to break due to human error. Imagine the example script above is to be attached to a player, and that ‘health’ is the player’s maximum health. Well, it probably has an upper limit, and it wouldn’t make too much sense for it to be negative, so we can use the Range attribute, with the syntax [Range(x, y)] (where x is the lower bound and y is the upper bound, both inclusive), to fix variables modified in the Inspector between two values.

tip_a_day_07_03
Sliders instantly make this 70% cooler. But I’m pretty sure Sliders Inc. paid me to say that.

This makes the values in the Inspector gain these neat little sliders too, which allows for a much more obvious representation of how large or small your variable’s value is compared to its maximum and minimum. Obviously Range can only be applied to variables of certain types – it wouldn’t make any sense applied to, say, an AudioClip – so make sure you only try using it with numerical types you can actually give a range to. Be careful in your code too – Range only impacts what you can set the variable as in the Inspector and doesn’t stop you freely changing it in code beyond Range’s, uh, range. However, it does make things tons easier for the designer since they won’t need to delve into the code to see any intended restrictions on what the variables’ values should be. And it seemingly has the nice effect of making your code twice as long.

This rounds up the first week’s worth of AGDTAD! I have plenty of ideas to continue the series (many A4 sheets were harmed in the making of this), so be sure to stay tuned for more funky and wacky ways to use Unity and other general game design tips! If you’re enjoying the series so far, be sure to share it with your friends and leave a comment if you want me to cover a certain area of game design in more detail.

A Game Design Tip a Day #6 – [Unity] Making Scene Construction Easier

In Unity, it can sometimes be a pain in the rear end to get your scene looking as perfect as you want it to. Not only does meticulously placing objects take ages, it can also be less accurate than if you have used features built into Unity to help you.

Snapping Tools

In order to assist with placing objects, Unity has a set of snapping tools. If you hold Ctrl/Cmd while moving, rotating or scaling an object, then that translation, rotation or scaling will ‘snap’ to multiples of predefined values. For example, by default, translations will only move in multiples of 1 in the X, Y or Z directions, and rotations will be in multiples of 15 for the three axes. The increments that Unity will snap to can be changed in Edit -> Snap Settings.

You can also snap vertices. If you have an object selected, hold V and then hover over any vertex of that object’s mesh or sprite corner and a little square appears over the nearest vertex/sprite corner to your mouse. Then, by clicking and dragging the object, the selected vertex will then snap itself to any nearby vertices of other game objects. Both of these tools, when used in conjunction, can be extremely helpful for placing modular geometry and tiled sprites.

tip_a_day_06

Resetting components

Another useful feature built into Unity is the power to reset components to their default values. This can be used for any given component (maybe a designer messed up some script’s values and you need to purge their sins from the face of the Earth), but when it comes to scene construction it serves a very helpful purpose – resetting the Transform component moves the object to local-space location (0, 0, 0), resets the rotation to (0, 0, 0) and changes the scale to (1, 1, 1). It’s also worth noting you can edit each individually by using ‘Reset Position’, ‘Reset Rotation’ and ‘Rotate Scale’ respectively. Just click on the small drop-down arrow in the corner of any component to bring down its drop-down menu.

tip_a_day_06_02

Easily positioning a camera

Sometimes it can be a real drag (hehe, drag) to get your camera into the correct position. To make it much easier, if you can position the Scene View camera to exactly where you want your in-game camera to look, you can then select the in-game camera in the Hierarchy view and press Ctrl/Cmd + Shift + F to move the in-game camera to the position the Scene View camera is in, looking in the same direction as it. Instead of remembering the shortcut, you can also select the camera and select GameObject -> Align With View from the menu bar. While we’re on that subject, you can also ‘Align View to Selected’ to move the Scene View camera to look at the selected object’s forward position, or Move to View to move the selected object to the Scene View camera without rotating it. All these options also work with any other object; they’re just especially useful for moving the camera because it’s so fidgety to work with sometimes.

Full-screening a window

This is something I didn’t know was possible until very recently. The Unity Editor has so many windows open that it can make each one quite small and hard to work with. With my setup I have the Scene View in the middle, landlocked by all the other windows, but sometimes it’d be very useful to have a larger area to move objects around in. Fortunately, you can press Shift + Spacebar while focused on a window to full-screen it.

tip_a_day_06_03

This should make it much easier to see what you’re doing while moving objects around your scene. There are treasure troves more tips for working with the Unity Editor, but these are the ones I think are most important for positioning game objects in the scene.

A Game Design Tip a Day #5 – [Design] The First Few Minutes of Your Game

The tips I’ve shared until this point have all been centred around scripting with Unity and using the Unity editor. This tip is going to be a more general discussion of the first few minutes or levels of your game. First impressions are extremely important, so you’ll want to grab your audience’s attention without completely overwhelming them.

Don’t overwhelm the player

In the first few levels of your game, it’s easy to just throw all the game mechanics at them in one fell swoop in the tutorial. Generally speaking, unless you have only one or two mechanics, this is bad because it’s simply too much for the player to handle. The best way to ensure the player gets a good grip on the core mechanics is to introduce them one at a time; show the player a brand-new mechanic and provide a safe area (one preferably without any deadly obstacles or risks) for them to test out the new mechanic, then put them in a relatively simple level that requires its use to proceed while allowing access to the safe area in case they need more practice. Making sure the player knows how to use a mechanic and has successfully completed a task using it will ensure that more complex later levels won’t present too many issues for them.

It’s also important to unveil your game’s signature mechanic early on, as this will be the focus of the game and keeping it behind a curtain for hours may make the start of the game feel like pointless warm-up. Portal 2 does an especially good job of drip-feeding new mechanics to the player and does all of the above very well – it even splits the Portal Gun tutorial into a single-portal device to smoothly introduce the concept of portals, weighted cubes and buttons, then proceeds to hand the player the dual-portal mechanic once they’ve mastered single portal placement. The backdrop of the first few levels of Portal 2 is also the familiar, yet now overgrown, scene of Portal 1’s introductory levels, which is a good technique to help the player feel ‘safe’ if you’re making a sequel.

tip_a_day_05_portal

Portal 2 lets you play with the single-portal device in a familiar level with no threats

A short story introduction or cutscene goes a long way

If your game is built around any kind of story (and unless it’s completely abstract, then usually it should have some story), then it’s best if you give the player some kind of story to invite their curiosity and make them want to finish levels in order to get the next piece of the story. A short cutscene (we don’t need any Metal Gear Solid levels of stuff here) should suffice. You can also use cutscenes and story plot points in quieter sections of the game (such as in-between levels) to break up the game into more manageable chunks; alternating between interesting action and quieter plot exposition can lengthen the game experience while keeping the player interested. Quiet sections also provide valuable exit points in your game – places the player can safely decide whether to keep going or stop playing without risking losing progress.

The start of the story is also where you ought to introduce most, if not all, of the main characters, as they’ll be driving most of the plot forward. It’s best to take the same approach here as with game mechanics; don’t throw a whole cast on the player at once, because a) that would be painful – people are heavy – and b) having to remember all these new characters will make the plot feel more complicated than it really is. This is where I personally think a game like Pokémon X and Y fell flat, especially if you were a newcomer to the series at this point – within the first 10 minutes you were introduced to Professor Sycamore, then Calem/Serena, then Shauna, Trevor and Tierno all at once, as well as the Pokémon you’ll likely be travelling with the whole game. I mean, I have far more gripes with the fact that the whole cast may as well be made of cardboard, but the main problem is that a lot of characters with distinct, ahem, ‘personalities’ are introduced at once. It’s a lot to take in.

tip_a_day_05_pokemon

Your friends would’ve been great in smaller doses. Or if they were actually, y’know, developed at all.

In summary, you want the first half an hour or so of your game to entice players with the first parts of a plot. Then, you want your main game mechanic, the one you advertise and put on the box art, to steal the show. After that, most of you game will be alternating plot points and gameplay (occasionally with new gameplay mechanics). The one thing you don’t want to do is scare away your player too early by shoving every mechanic you’ve got at them. It’s kind of like fishing, except you don’t want to shoot yourself.

A Game Design Tip A Day #4 – The Wrath of the Garbage Collector

In many programming languages, there is something called the garbage collector. No, not the truck that comes by your house every week to collect your empty pizza boxes and energy drink cans. When you create objects, generally speaking they are added to what’s known as the heap, which is like a big pile of data used by all your programs. When you’re done using a piece of data, then the garbage collector comes along and frees up that memory for re-use later; without it, the heap would soon fill up with gunk and memory leaks and your computer would probably crash. And that’s bad.

There are certain operations notorious for garbage collection. One of those, in most languages, is string concatenation. Strings, as you’re probably aware, are objects. Like all objects, they occupy space on the heap. When you concatenate two strings together, it’s a common misconception to assume there isn’t much overhead and you’ll just be getting a bigger string back out. However, since strings are usually immutable (once set, their values can’t be changed – this is the case in languages such as Java and C#), you’re actually taking the two original strings and creating a third immutable string which contains the contents of the original two (or three, or four etc). You might see something like this in code (this example is specific to Unity C#):

tip_a_day_04

and think it looks reasonable – it’ll print the line “Player John has 0 health”. However, you’re taking five strings – “Player “, “John”, ” has “, “0” and ” health.”, and then creating an entirely new string to print. What’s worst about this is since “Player “, ” has ” and ” health” were created on-the-fly and are no longer needed, they need to be removed from the heap, which means the garbage collector is called and we waste a load of time cleaning up space we didn’t need to allocate in the first place. A better solution would have been to cache those three strings somewhere (such as in their own variables) so they’re not wastefully created and immediately removed again. That also has the advantage of removing the overhead of creating them each time, especially if PrintStuff() were called frequently.

A Unity-specific warning zone for garbage collector abuse are the Instantiate() and Destroy() functions (although all scenarios in which objects are made and destroyed have the same effect). A common operation in games, for example enemy spawning or playing particles, is to create them when required using Instantiate() and then remove them once they are no longer needed using Destroy(). Each time Instantiate() is called, there is overhead for creating the object, and when Destroy() is called, the garbage collector gets involved. This means that overuse of these functions can lead to a significant performance decrease. It’s like how capitalism works – why re-use this old thing when I can buy a new one?

A much better way of working with multiple objects this way is to utilise object pooling; that is, we create a bunch of objects at the start of the game in a disabled state, enable them when we’d usually have instantiated them, then just disable and reset their parameters ready for re-enabling, when we’d previously have destroyed them. We still have a large overhead at the start because we need to create everything, you need to make the pool large enough for the maximum number of objects you’re likely to need (or the pool has to be extendible) and there’s only a point to this if the speed improvement is significant (on small object sets, this could actually be slower), but in games where things are frequently spawning and disappearing, object pools are more likely than not the way to go. Besides, it’s more amusing to code up a really big pile of stuff than an boring old create/destroy cycle. Yaaaaaawn.

A final bad Unity thingamajig is this innocent-looking thing here:

tip_a_day_04_02

It looks fine, but there’s one deceptively-demanding call here: GetComponent(). Behind the scenes, this sneaky little fucker is grabbing a whole list of components on your game object just to find your singular component, then sending the list to our good ‘ol friend, the garbage collector. It’s best if you can avoid use where possible, or at least limit use to Start(). One good design tip is to have a sort-of ‘manager’ in your scene that, at the start, you send references of objects to without using GetComponent() – for example, from my PlayerController class, I send my GameManager a reference to the PlayerController for anyone to access. Then whenever I need to reference PlayerController, I can find it through GameManager rather than using GetComponent() all over the shop. It’s also far more elegant, since I know where I can find all the references I’ll need.

A Game Design Tip A Day #3 – [Unity C#] HideInInspector Attribute

Yesterday I talked about the [SerializeField] attribute and how useful it can be for programmers to uphold good software engineering principles while allowing level designers to change variables. Today I’ll talk about the exact opposite, when you need a public variable, but you want designers to keep their filthy mitts off it. Step forward [HideInInspector].

tip_a_day_03

As you can see, anything with the HideInInspector attribute won’t get shown in the inspector. Does what it says on the tin really!