Using Visual Studio Code with Unity

Using Visual Studio Code with UnityMicrosoft recently released Visual Studio Code, a cross-platform, lightweight IDE based on GitHub Atom worth considering as an alternative to MonoDevelop. Unity’s team has decided to stop distributing Unity with MonoDevelop for new Unity versions. Instead, you will get Visual Studio Community bundled. Unfortunately for Mac and Linux users, you’re still bound to use MonoDevelop as default. Let’s try something else!

Don’t confuse Visual Studio Code with the full version of Visual Studio. They are completely different applications! Visual Studio Code gives you only a small portion of what Visual Studio can do. It still can be quite powerful, though.

visual studio code running

Installing

To get started you need to download and install Visual Studio Code for your target platform. In order to do so, go to this page and download package suitable for your operating system. After you get the package, follow the standard installation procedure for your operating system.

Configuring Unity

In order to make your Unity editor work with Visual Studio Code, you have to unpack a UnityVS plugin into your project. Unfortunately, you have to repeat this process for all projects that you want to work on with Visual Studio Code.

After unpacking it, go to the Preferences window (Edit -> Preferences for Windows and Linux or ⌘, shortcut on Mac OS).

vscode preferences window

Here make sure that for VSCode tab Enable Integration checkbox is enabled. When done, you will be able to open your project using Open C# Project In Code menu option.

Possible issues

When running on MacOS it’s quite common to get an error like this one:

vscode omnisharp error

To fix this issue, run these commands to update mono:

Summary

You can find more information about VSCode and Unity here. If you won’t be satisfied with it, you can always remove the VSCode directory from your project and then automatically get back to MonoDevelop.

How to Make a Custom Editor Window in Unity

Today we will cover creating custom Unity editor windows. They can be used in many different ways. Most probably you know them from 3rd party assets. Even if you’re not an asset developer, creating custom windows may help you greatly with your game development!

One of good examples of how the custom Unity editor window may be used is an implementation of in-editor cheat subsystem. Some time ago we created a cheat subsystem that is working within the actual game. Implementing some cheats using the editor windows has one significant advantage – it’s much, much easier to write and use! Read this article further on to learn how easy it can be!

Creating an editor window

First, we have to create a new window. In order to do that, we need a new class inside Editor folder (see Special Folder Names).

editor cheatswindow script

Then start with code like this:

Let’s explain:

  • At line 4 we have to make CheatsWindow class, a derived type of EditorWindow class
  • At line 6 we’re telling that the following method should have a Unity menu entry. It will be available at My Game/Cheats in this case.
  • At line 7 there’s a static method to create a window.
  • At line 9  a window is created (if does not exist) or focused (if exists) – see GetWindow documentation.

When the Unity compiles this code, you will notice a new menu entry.

cheats menu entry

Try clicking on it, and a new empty editor window will appear!

empty editor cheats window

Now let’s try to fill it with some content!

Adding content

To add content to our new editor window we have to implement OnGUI method just like for MonoBehaviour classes. The only difference is that you now have the access to EditorGUI and EditorGUILayout classes, but still you can use GUI and GUILayout classes as well! Let’s try it.

447e407b-2722-4b95-91ba-734c130bf7b7

That was easy! But as you might have noticed, you won’t be able to edit the data just then. GUI functions are returning a new value as a parameter and a current value should be passed as a second parameter to make it work. Let’s implement new Cheats class. This one will be located outside the Editor directory so the game script will be able to access it. Watch out, this is a big one!

OK, let’s split it to smaller parts.

#if and #endif are so-called preprocessor directives. The #if UNITY_EDITOR evaluates to true if UNITY_EDITOR symbol is defined. The Unity defines UNITY_EDITOR symbols when you’re working in the editor, but not when you’re building your game to the target platform. That way using UnityEditor; will be stripped-out when you build your game (see Platform Dependent Compilation). And this is necessary, because the Unity compiler will yield an error if you try to use the UnityEditor namespace inside game scripts without any environment check.

Next, we have a property:

And the getter:

This is working very similar to previous preprocessor construction, but here you also have an #else directive. The #else code block will be included if the #if condition evaluates to false. Simply talking, inside the Unity editor this code will get boolean value form EditorPrefs, and outside the Unity it will always return false.

Setter is very similar to getter, but here we don’t need an #else directive, because we don’t want it to set anything outside the Unity editor (there will be nothing to set it).

The rest of the file consists of two more properties with similar construction.

Now let’s modify our window code:

As you can see, since we made our cheats data this way, it’s really easy to read and save the persistent data. Now, even if you restart your Unity editor, the cheats will be still in effect!

Adding buttons

How about a reset button? That’s easy!

cheats reset button

But by default the reset button is quite big and located right below other fields. This makes our window look kind of unfinished. Let’s fix that using GUILayout.FlexibleSpace() before rendering our button.

cheats one flexible space

Now if you want your button to be smaller you have to play with EditorGUILayout.BeginHorizontal() and flexible space.

cheat window two flexible spaces

And maybe a final touch.

cheats window final touch

The package

As always you can download the unitypackage containing scripts described above. Feel free to download, modify and adjust it to your own needs!

A Story of NullReferenceException [Part 2]

This is a story of NullReferenceException part 2. If you haven’t read the part one, you can still do it here.

Don’t trust GetComponent()

GetComponent() is a commonly used function to access current GameObject’s component. Here’s a code snippet showing how to disable object’s renderer, so it is no longer visible in the game view.

Of course GetComponent() will return null if current object doesn’t have the requested component.  That is a serious risk, because components can be easily removed by the designer at any time without any warning.

Use [RequireComponent]

First you should use [RequireComponent] annotation whenever it is possible.

Note that [RequireComponent] will not guarantee that given component is always available. What it actually does, is adding missing component during object setup. Nothing fancy, but it lowers the risk of NullReferenceException a little.

Decide what to do on failure

Yes, you definitely should do a null check. But you have to decide what you want to do if the component happens to be missing. You have three options in general.

  1. Display an error and ignore.
  2. Report the incident as bug.
  3. Try to recover.

As you can see there’s no option for throwing an exception. That’s because we want our game to be as stable as possible.

1. Display an error and ignore

This is the easiest way to handle these kind of bugs. If you encounter them when working in Unity Editor then you will have a good opportunity to fix it before it is even released. Yet your situation will not be that comfortable if this issue appears on your player’s devices that usually you don’t have direct access to.

Please note that on line 7 I wrote if (renderer) instead of if (renderer != null). That’s because the UnityEngine.Object is overriding the (bool) operator and under the hood this is a nice shortcut to do a null check.

2. Report incident as bug

If you have the opportunity, you may want to report this incident as a bug. Automatic bug reporting helps you to fix bugs in production, so you should seriously consider this kind of implementation. Of course you have to ask your player for a permission to send a bug report, because otherwise it may violate the agreement with Google Play or App Store and as a result your application may get banned.

I am personally using a script called SRDebugger from the Asset Store. It allows to display an overlay form that enables sending a bug report to my e-mail address.

Alternatives:

3. Try to recover

This is the third option and the only one that allows your game to work properly. I believe it should never be used, because if there’s a smoke then there’s a fire. Recovering is only hiding the smoke while you should start looking for the fire.

Assert GetComponent()

Remember that you should look for any issues as soon as possible. If your script is using a component sometime in the future, make sure to check at the beginning if this component is available.

Watch out for callbacks!

If your game includes callbacks that are called from external code and/or from another thread you may find yourself in a situation, when NullReferenceException is thrown out of nowhere. It can happen with Social API when callback may be invoked seconds after making a request. And at that time the object that made a request may… no longer exist.

OK, that’s not really true, but we can run into fake null issue here that we were talking about before. Let’s consider a scenario like this:

  1. Results scene is loaded.
  2. ResultsScreen script is requesting Social API for current player’s score.
  3. The player clicks on “main menu” button.
  4. Results scene is unloaded.
  5. Main menu scene is loaded.
  6. Social API callback is being invoked inside ResultsScreen script.

So if Results scene is unloaded, all of its objects should be destroyed at the time of executing sixth step. That’s not true, because the reference to ResultsScreen object is still valid and object exists, but it reports itself as null by faking its own null check as I explained in the previous article. It may look like this:

Can you guess where you will receive a NullReferenceException? On line 10 and it really doesn’t matter if ScoreLabel has been assigned or not. You won’t be able to access it at this point.

How to protect yourself from this kind of situations? The answer is strange but simple. You should do a null-check of this.

Yes, that’s right! Current object won’t be null because it simply cannot be, but since Unity is faking null checks, this is the best way to check if the current object can be still used!

Of course you can null-check all your objects that you’re about to use, but in more complicated scenarios this may be simply too much. Checking this for null should be good enough.

Keep calm and singletons

Singletons are often perceived as anti-pattern. Still singletons are widely used because of the simplicity and ease of implementation.

In the Unity most common type of singletons are:

  1. Singletons created on demand
  2. Singletons created by the engine (derived from MonoBehaviour)

Let’s look at the second type of singleton.

First, you should make sure that singleton Instance field is assigned as soon as possible, so I’m assigning it in Awake() method. But that’s not enough. There’s a serious risk that Awake() will not be called even once. This risk is caused by the assumption that Singleton object exists on the scene.

Knowing that, you have to create an assert in each class, where you intend to use this singleton:

Note that I’m assigning a singleton in Awake() function, but I’m testing it for null in Start() function instead of OnEnable() function.

That’s because Awake() and OnEnable() functions are called one after another for every enabled GameObject. It’s not explained too well in the official documentation, so I will try to clarify that.

There are scripts: ScriptA and ScriptB both with Awake(), OnEnable(), and Start() functions. The call order may look like this:

  1. ScriptA: Awake()
  2. ScriptA: OnEnable()
  3. ScriptB: Awake()
  4. ScriptB: OnEnable()
  5. ScriptA: Start()
  6. ScriptB: Start()

So as you can see, you cannot be sure that when you’re in OnEnable() that all singletons are assigned. The risk is even greater that sometimes singleton may be assigned, and sometimes not!

You can force your script to be initialized before anything else using Script Execution Order, but to be completely safe, don’t use singletons in Awake() and OnEnable().

Suggestions?

Do you have any other interesting suggestions on how to make your project robust by securing your code against NullReferenceExceptions? Please share your suggestions using the comment form below! We will appreciate it!

A Story of NullReferenceException [Part 1]

Once upon a time there was a little boy living with his mother alone between the mountains. They lived a peaceful life. One day the boy’s mother got very sick. The boy called for a doctor, the best in the valley. When the doctor finally came, he examined the woman. Unfortunately, there was only one medicine for her illness and this medicine was very hard to get. The only known location was far away from there, on very dangerous lands, full of traps and monsters. Without thinking too much, the boy took his wooden sword, backpack and he went on a trip where… NullReferenceException.

NullReferenceException

If there’s one thing that is common for most of Unity games, this thing is NullReferenceException. This little fella can be quite a nuisance, especially on mobile platform, where you most probably want to have a script call optimization set to Fast But No Exceptions. That’s because any exception will cause your application crash immediately. Is this worth the risk? It depends on the time your game requires to execute all the scripts in each frame.  The more time it needs, the more you will benefit from enabling the optimization.

What NullReferenceException is?

Before killing the dragon, we must fight the dragon. Before fighting the dragon, I would say that we have to get to know the dragon. NullReferenceException is so common issue, that is has its own Unity documentation page! But let’s compare it with official .NET documentation definition.

Official:

In this article we will talk about techniques that will help you minimize NullReferenceException occurrence possibility.

Unity:

A NullReferenceException happens when you try to access a reference variable that isn’t referencing any object. If a reference variable isn’t referencing an object, then it’ll be treated as null.

So this means that if you have a reference (field or variable) that is not pointing to any object (is null) and you try to access it (access parameter, field, or execute a method of this non-existing object), then you will receive a NullReferenceException.

But… there’s one subtle, yet important, difference with NullReferenceException when working with Unity objects. Normally, you may do a check if an object is null before trying to do anything with it:

But Unity objects are a bit different. Unity objects can report themselves as null even if they are still referencing an object!

No, that’s not a bug! Some referenced objects are scene objects. Imagine what happens if a scene is being replaced by another scene – all regular scene objects have to be destroyed. Since Unity cannot update your valid references inside your code (they still will be valid after destroying the scene), it is faking a null check for those that you are still referring to, so it will (should) stop you from use these any longer. In case you do try to use any of these objects, you may receive a message like this one:

reference object destroyed

It is also an exception that will crash your app, so be warned!

Fail Fast

The worst and yet the most common case of NullReferenceException is when your component expects some other objects to be passed into it through the inspector, but for some reason somebody didn’t do it.

The example above is a simplified situation when you want to display a label when player touches the star. Collider other is guaranteed to be a valid reference (based on documentation), but what we cannot be sure about, is the scoreText field that should be visible in the inspector. What if somebody forgets to assign it? You will know about it only after trying to touch the star. That’s definitely too late!

We can handle these kind of situation using Asserts (we talked about asserts before). Asserts will tell us if something is wrong, and it’s a wise choice if all the checks can be done right after the scene is launched. Let’s try to add an assert like this:

This code will yield an error right after the scene is started. We no longer have to wait for the player to touch the star. That way we can check if everything is OK with the scene just by launching it!

Do I have to add an assert for each inspector object? Yes! You cannot trust that someone  doesn’t break your scene references.

Public field is not bulletproof

Have you noticed that public fields can be accessed from any place? Yep, this can be bad. This means that any other script may get to it and set it to whatever it wants to. Assert won’t help us if other script will decide to replace our reference in the middle of playing the game.

To make it a little more bulletproof, we can make it private. Private fields can be displayed and assigned within the inspector, but a field like that needs a [SerializeField] annotation:

Now, the field cannot be accessed outside the current object what makes the risk of unexpected NullReferenceException significantly lower.

To be continued…

You can read the second part of this article here.

Wrong Import Settings are Killing Your Unity Game [Part 2]

There are many things that may go wrong with your game development. Your models may have too many triangles for your target platform to handle, your algorithms may be too expensive for your CPU, and also you may be using too many materials so batching won’t work efficiently. These are difficult issues, and you as a game developer should always remember to keep good balance between visuals and performance. Yet, there are some things so simple that we often forget about their existence, but these can have a serious impact on your game performance.

Last time, in Part 1, we talked about how texture import settings can kill your game performance. This time we will talk about sound import settings and why it matters.

Audio Clip Import Settings

When working with Unity many things can keep their default settings set and everything will be working just fine. Of course, defaults are not optimal in most cases, but your game should be working OK. This rule unfortunately does not apply to Audio Clip Import Settings.

Audio Clip (sound files) importing is working very similar to texture importing. Unity supports many different audio formats, but in the end it converts them all to preferred (by the engine) format. Currently, in Unity 5.2.1 this can be PCM, ADPCM, Vorbis/MP3 and HEVAG. Note that not each platform can handle all of these compression formats, and some platforms have only one format available (e.g. WebGL can work only with AAC audio clips).

Memory matters

All Audio Clips are imported by default with “Decompress On Load” Load Type and “Vorbis” Compression Format.

These are default import settings.

These are default import settings.

You should be very careful with this setting, because using it on all your audio clips (Unity does it by default!) may consume large amount of your game’s memory! Do you see the info box on the screenshot? Original file size is computed to 35.9 MB and the imported size to 10.7 MB. This means that this Audio Clip will increase your game (archive) size by 10 megabytes, but playing it will require nearly 36 megabytes of RAM! This does not sound too scary if you’re building a game for PC where it is quite common to have 8 gigabytes of RAM, but mobile devices are still very limited on that manner.

When I should use specific Load Type?

Let’s get this straight. Each Load Type and Compression Format combination can be used and you’re the one who knows best which one should be chosen. There are three Load Types:

  • Compressed In Memory – Audio Clip will be stored in RAM and will be uncompressed when played. Does not require additional memory for playing.
  • Streaming – Audio Clip will be stored on a device persistent memory (hard drive, flash drive etc) and streamed when played. Does not require RAM for storing and playing (at least this value is not significant).
  • Decompress On Load – Audio Clip will be stored in RAM uncompressed. This option requires the most memory but playing it won’t require so much CPU power as the rest.

So, which one to use? It depends…

Music and/or Ambient Sounds

Music is stored in long Audio Clips so it can consume a lot of memory. For sure, we don’t want music to be decompressed into the memory then played. You have two options here:

  1. Use Load Type “Streaming” and Compression Format “Vorbis”. This combination will use the least amount of memory but will require some CPU power and disk I/O throughput.
  2. Use Load Type “Compressed In Memory” and Compression Format “Vorbis”. The only difference from the first solution is that it will exchange the disk I/O with some memory requirement. Note that you can adjust the Quality slider to decrease compressed clip size in exchange of sound quality. Usually 100 percent is a way too high. I would recommend something around 70 percent.

Note that if you have more than 2 music/ambient sounds clips playing like this, it can consume a serious amount of CPU power.

Sound Effects

Sounds effects are usually short or medium Audio Clips. Also these can be played frequently or rarely. Here are some rules:

  1. For frequently played and short Audio Clips use Decompress On Load and PCM or ADPCM Compression Format. When PCM is chosen, no decompression is needed and if audio clip is short it will load very quickly. You can also use ADPCM. It requires decompression, but it is much lighter to decompress than Vorbis.
  2. For frequently played but medium Audio Clips use Compressed In Memory and ADPCM Compression Format. ADPCM is around 3.5 times smaller than raw PCM and decompression algorithm will not consume as much CPU as Vorbis.
  3. For rarely played and short Audio Clips use Compressed In Memory and ADPCM. For the same reason as described in point 2.
  4. For rarely played and medium Audio Clips use Compressed In Memory  and Vorbis Compression Format. This SFX might be too long to be stored using ADPCM and played too rarely, therefore additional CPU power required to decompress wouldn’t be a such pain.

Summary

Always remember to check your Audio Clip Import Settings. These are silent performance killers of your game. Set these right, and you will get additional CPU power for things that matters.

Also please take a look at the manual for technical information about import settings.