Optimize yourself! [Part 2]

Things you can do better in Unity!

This is the second part of our tips list, that can help you increase your productivity with Unity.

The first part can be found here. So definitely check it out if you haven’t already!

1. Unity project setup wizard

When you’re creating a new project it often takes at least half an hour to setup everything. There are at least 2 ways for you to save time here:

  1. Simple: create a project template with basic setup, folder structure and version control ignore file. This will be the most efficient one to make and you can put stuff in it already. But it is not the most customizable one, so probably you will need to spend this additional time on finishing your configuration.
  1. Advanced: create a module that will be responsible for setting up your whole project in a way you want it. With as many game/folder structure/architecture variants as you’d like to have. And in a perfect world, it would be great to have such module but it takes time to make it.

No matter which option you choose, it is always helpful to have a solid foundation for you project 😉

2. Finally you drag the list of objects into the component

Sometimes you may come across a case where you have to fill the list of objects with objects from a scene or a project. When you’ll first try to select all of the objects you’d like to assign, you’ll realise that Inspector is no longer showing you object with your list to fill. There is a very simple solution to that, and not many people know about it.

In a top right corner of Inspector there’s a lock button, that locks Inspector focus on current view.

Now you can select as many objects as you like and you can easily drag and drop them all into the list in Inspector.

Done!

3. Use build-in json tools

Normally, when you are working with JSONs, you have to have JSON parser. After parsing a string into JSON object, you have to assign all the values from JSON to the desired object, which is super boring to write each time…

However, since the Unity 5.3 they gave us built-in JsonUtility which will do most of it for you!

Warning: JsonUtility currently works only with ‘structured’ JSON and does not support types, like dictionaries. If this is a problem for you, then you probably need to find a fully-featured JSON library.

For more information about JsonUtility you can go to: https://docs.unity3d.com/Manual/JSONSerialization.html

4. One script that handles all of the platforms?

If you are new to programming, you probably don’t know much about platform dependent compilation. If you are into programming, then you have probably seen a code that uses platform dependent compilation a few times, but you might not understand how it works. It’s simple! It gives you the power to write the code that will be executed only on a specific platform. So you might ask why it’s good to use it? Because you can use libraries designed only for one platform.

For example: you are making the greatest game of all time for Android and iOS. And you want to implement that last feature, namely leaderboards. You’ve created a button to show these native leaderboards and assign method OpenMainLeaderboard() to it. And now it’s time to implement this method, but how will you run Google Play Services on Android and Game Center on iOS?! That’s simple! Use platform dependent compilation!

Example:

With that you don’t have to worry about the missing references from libraries that are not designed to run on other platforms.

If you’d like to find more platform directives go to: https://docs.unity3d.com/Manual/PlatformDependentCompilation.html

5. Don’t waste your time for reimporting project over and over again

Aren’t you tired of waiting for your project to be reimported each time you change build platform? For me it’s not only boring, but also wasting a lot of time! But there is a mighty solution for that, which no one ever told you about!

In Unity there is something called Cache Server. It can be configured to work on your local machine or on a dedicated server. This cache server will save your reimported assets and when you change your build platform, it will give you back your reimported assets, so you don’t have to reimport them again! This is great! And the only thing you have to do is to go to Unity > Preferences > Cache Server and change Cache Server Mode to Local or Remote.

You can read more about Cache Server on our blog:

http://blog.theknightsofunity.com/using-unity-cache-server/

http://blog.theknightsofunity.com/unity-cache-server-localhost-make-sense/

Summary

That was top 10 things that you can do better in Unity (with those in the  previous part)!

I hope that this list will help you save a little more time that you will still waste by watching another cat video on the internet 🙂

If you have your own trick to speed up your work, then don’t hesitate to share it in a comment section below.

And don’t forget! Optimize yourself!
You can also subscribe to our newsletter, so you won’t miss our posts in the future!

Optimize yourself! [Part 1]

Things you can do better in Unity!

How many times you’ve been bored or annoyed because of some stuff you had to do over and over again? Probably countless… But fear no more!

Bill Gates once said “I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.”.

And you might ask why even I’m bringing this quote here? It’s because I am going to make you lazy in a good way… 😉

Let’s get it started

The main reason we came up with idea for that list is the fact that we (as  humans) are lazy by design and we don’t like to repeat ourselves in our daily tasks. As a  result, we came up with tools and tricks that we use to make our life easier and we hope to make it easier also for you!

So here are top 10 things you can do better in Unity:

1. Change your play mode editor color!

How many times you’ve been tweaking your game to be in this one perfect spot? And all of a sudden you realized that you just clicked on pause button and lost all of those changes? Of course this is how Unity works, but how many times you forgot about it? Probably not only once. 😉

So the simplest solution to remind you that you’re in the play mode is to change editor’s play mode color! To do so, just go to Unity > Preferences > Colors and change your Playmode tint color to something more vivid.

Results?

2. Let the code write itself

There are many tools that can extend your IDE and give you just a little bit of support for your programming skills. One of such extensions is JetBrains ReSharper which is so useful that you probably won’t want to program anything without it.

This tool analyzes the code for you. This tool writes the code for you. This tool finds bugs for you. THIS TOOL EVEN FIX THOSE BUGS FOR YOU! Maybe not all of them, but it fixes the typical ones without any problems 😉 If you are programmer then you should definitely check it out.

Here are some examples:

  • Converting code to Linq:

  • Converting code from Linq:

  • Adding missing usings:

  • Generating methods:

Home page of ReSharper: https://www.jetbrains.com/resharper/

3. Optimize your build pipeline

When you’re developing your next very best app or game you are probably making a lot of builds per day. Each build can take up a few minutes or even an hour to make. This is bad especially because it’s impeding your work till the build is finished.

So let’s count the time you waste because of that process. Let’s say that your project is medium sized and need ~20 minutes to build on Android and ~1 hour to build on iOS. And you’re making 1 build per day at minimum. Now let’s sum up the time it takes to make those builds in one month (20 work days): Android builds – at least 6h 40m. iOS builds – at least 40h. This is more time than it took first spacecraft (Luna 1) to make flyby of the Moon in 1959! Which took only 36h! But how to save so much of your time? Use external tool to make those builds for you!

For a long time, the most popular one was Jenkins, which offers you a lot of flexibility. Also, it’s giving you basically unlimited possibility to configure your build pipeline to suit your needs, for example:

  1. Watch repository for new commits.
  2. Analyze code.
  3. Make a build.
  4. When finished, send build file to a FTP server.
  5. Send mail with a build report and a link to build file.

Of course there are a lot more options, and if you ever need more, then you can always add some. Oh, and I almost forgot! It’s available for free! So you just need to go to their website, download it and install it on your build machine 😉

More about Jenkins: https://jenkins.io

The other tool is provided by Unity itself and it’s called Unity Cloud Builds. It of course assures better integration with editor, where you can basically configure everything you need to start using it. Like Jenkins, it is also available for free, but with Unity subscription your builds will be higher in priority list and will be processed faster. Additionally, after each build Unity generates the link to your build to download or to share with your friends 😉

More about Unity Cloud Builds: https://unity3d.com/services/cloud-build

So what are differences between these two? Jenkins is open-sourced and has a huge library of plugins to install. You can for example integrate 3rd party APIs like Slack with it. Jenkins also allows you to configure it any way you like it and give you a possibility of setting up your own build pipeline. On the other hand, Unity Cloud is only focused around Unity and you can’t add anything to it. Of course you can configure Slack to get notifications from Cloud or use Webhooks that Unity provides, but that’s it. But the advantage is that it is straightforward, easy to configure and use.

Which one should you use? If you need something simple, then go with Unity Cloud Builds. If you need something more advanced, with a lot of configuration options, then go with Jenkins.

4. Store your data in convenient way

Many people put the data into objects on a scene or hardcode it somewhere else. With that approach it’s often hard to find where you have to make a change in order to achieve a desired result later in development…

But we’re here to present you two better ways to store data:

  1. Text Asset, which can be JSON, Excel file or any other text format. The problematic aspect of it is that in such file you can put only text, and you need to have a parser to read this file and get your data.
  2. The other and more convenient way is to create ScriptableObject. You can put there anything you like. Text, numbers, textures, material, models, etc. And most important thing is that you can use it like any other asset in your project and reading data from it is as easy as getting a variable.

Here is an example of ScriptableObject code:

And with that code you can easily create as many WeaponData objects as you want 😉

5. Auto references

Creating UI is not the most pleasant thing to do, mostly because you have many scripts, that need even more references, which you have to assign by hand. Wouldn’t it be great to have all of these references filled all by themselves?

Of course! Here is a sample implementation for that:

Here is class example of use of that implementation:

Here is how it looks in Unity:

These references were added automatically! 😉

Summary

So, here’re 5 tips that hopefully can help you exclude a chore part from the Unity development process and boost your productivity. I’ll be adding more tips like that in the next part, so stay tuned!

You can also subscribe to our newsletter, so you won’t miss our posts in the future!

MonoBehavior calls optimization

What if I told you that Unity can be wasting a lot of CPU performance just by calling your MonoBehaviour functions? It doesn’t really matter what your scripts are doing. If you have hundreds or thousands of them, you should be aware that there’s a new field of optimization.

Magic methods

MonoBehaviour functions calls are slow. And I’m talking about functions like Update(), LateUpdate(), OnRender() etc. They are so-called magic methods, and if you’re familiar with object-oriented programming languages, this concept looks like calling a method using reflection mechanism (reflection enables method calls even if you don’t know the interface). Reflection calls are expensive, so Unity does everything that is possible to cache any operations, so the set of CPU instructions needed to call a magic method each frame could be minimal. But it can still be slow, very slow…

Why is it so slow?

I’m not gonna talk about the details (but if you really want to read about the details, look at the end of this article for the links), so just imagine that Unity tries to be as flexible and easy to use as possible. Making something easily costs CPU power because the engine cannot make any assumptions about your game and it needs to do a bunch of checks to call your magic functions on the right objects, in the right order, and to not crash in the meantime.

Can it become faster?

Oh this is my favorite part. Yes! It can! How? You have to take the responsibility of calling Update() function by defining your own function and calling it from a manager. This way, you’re taking responsibility for updating your objects. How much faster it can become? Well, it depends on the platform. Let me use the measurements done by Valentin Simonov on official Unity blog:

Mono with fast but no exception settings.

Here you see that the difference can be worth the time. This is a measurement of calling Update() 10000 times.

Writing a manager

I will present a fairy simple example of a manager called BoxManager that is managing BoxManaged scripts. Manager has two responsibilities:

  1. Keeping the list of managed objects updated
  2. Calling update-like functions on managed objects when manager Update() is called.

The code may look like this:

As you can see, it’s really simple. Before implementing Update() function let’s take a look at BoxManaged.cs.

It registers itself when enabled and de-registers when disabled. Fair enough. ManagedUpdate() function is a function that will replace Update() magic function. Let’s implement BoxManager.Update(), so it will be able to call all BoxManaged.ManagedUpdate() at once.

And that’s it! Really! Now in ManagedUpdate() you can do everything you would normally do in the Update() function.

Please note that I did not use foreach for iterations. Firstly, because it’s generating small amount garbage Unity’s version of Mono. Secondly, because it simply seems to be slower.

Should I care?

It depends on what kind of game are you creating and what is the target platform. Ask yourself a question – do you have many MonoBehaviour objects with Update() calls? It doesn’t necessarily need to be Update(), it can be anything that it is invoked with each frame. Then, if you’re targeting mobiles, it’s definitely worth to try! Targeting standalones? It’s still something you may consider, especially if you’re planing to have huge amount of objects.

Sometimes you may need a manager even if you’re have a relatively small amount of objects. On iOS there was (I don’t know if it has been fixed or not) a problem with OnRender() function. Having it on 30-40 objects could decrease the game’s performance twice! The solution? A manager like the one presented above, but instead of calling Update() it should be calling OnRender() code. Yes, it will work!

Please keep in mind that this is one of many optimization strategies that you can use. Yet this one is quite hidden – unless you know about it, you will have a hard time to find about this one. That’s the reason why this article has been brought to life.

References:

https://blogs.unity3d.com/2015/12/23/1k-update-calls/

 

Snow Shader Tutorial with Unity

Let It Snow! How To Make a Fast Screen-Space Snow Accumulation Shader In Unity

Have you ever wondered how much time does it take to apply snow to all of the textures in your game? Probably a lot of times. We’d like to show you how to create an Image Effect (screen-space shader) that will immediately change the season of your scene in Unity.

3D model house village with trees in the background in Unity

How does it work?

In the images above you can see two screenshots presenting the same scene. The only difference is that in the second one I enabled snow effect on the camera. No changes to any of the textures has been made. How could that be?

The theory is really simple. The assumption is that there should be a snow whenever a rendered pixel’s normal is facing upwards (ground, roofs, etc.) Also there should be a gentle transition between a snow texture and original texture if pixel’s normal is facing any other direction (pine trees, walls).

Getting the required data

For presented effect to work it requires at least two things:

  • Rendering path set to deferred (For some reason I couldn’t get forward rendering to work correctly with this effect. The depth shader was just rendered incorrectly. If you have any idea why that could be, please leave a message in the comments section.)
  • Camera.depthTextureMode set to DepthNormals

Since the second option can be easily set by the image effect script itself, the first option can cause a problem if your game is already using a forward rendering path.

Setting Camera.depthTextureMode to DepthNormals will allow us to read screen depth (how far pixels are located from the camera) and normals (facing direction).

Now if you’ve never created an Image Effect before, you should know that these are build from at least one script and at least one shader. Usually this shader instead of rendering 3D object, renders full-screen image out of given input data. In our case the input data is an image rendered by the camera and some properties set up by the user.

It’s only the basic setup, it will not generate a snow for you. Now the real fun begins…

The shader

Our snow shader should be an unlit shader – we don’t want to apply any light information to it since on screen-space there’s no light. Here’s the basic template:

Note that if you create a new unlit unity shader (Create->Shader->Unlit Shader) you get mostly the same code.

Let’s now focus only on the important part – the fragment shader. First, we need to capture all the data passed by ScreenSpaceSnow script:

Don’t worry if you don’t know why we need all this data yet. I will explain it in detail in a moment.

Finding out where to snow

As I explained before, we’d like to put the snow on surfaces that are facing upwards. Since we’re set up on the camera that is set to generate depth-normals texture, now we are able to access it. For this case there is

in the code. Why is it called that way? You can learn about it in Unity documentation:

Depth textures are available for sampling in shaders as global shader properties. By declaring a sampler called _CameraDepthTexture you will be able to sample the main depth texture for the camera.

_CameraDepthTexture always refers to the camera’s primary depth texture.

Now let’s start with getting the normal:

Unity documentation says that depth and normals are packed in 16 bits each. In order to unpack it, we need to call DecodeDepthNormal as above seen above.

Normals retrieved in this way are camera-space normals. That means that if we rotate the camera then normals’ facing will also change. We don’t want that, and that’s why we have to multiply it by _CamToWorld matrix set in the script before. It will convert normals from camera to world coordinates so they won’t depend on camera’s perspective no more.

In order for shader to compile it has to return something, so I set up the return statement as seen above. To see if our calculations are correct it’s a good idea to preview the result.

RGB Rendering of Camera Space for Unity Shader Tutorial

We’re rendering this as RGB. In Unity Y is facing the zenith by default. That means that green color is showing the value of Y coordinate. So far, so good!

Now let’s convert it to snow amount factor.

We should be using the G channel, of course. Now, this may be enough, but I like to push it a little further to be able to configure bottom and top threshold of the snowy area. It will allow to fine-tune how much snow there should be on the scene.

Snow texture

Snow may not look real without a texture. This is the most difficult part – how to apply a texture on 3D objects if you have only a 2D image (we’re working on screen-space, remember)? One way is to find out the pixel’s world position. Then we can use X and Z world coordinates as texture coordinates.

Now here’s some math that is not a subject of this article. All you need to know is that vpos is a viewport position, wpos is a world position received by multiplying _CamToWorld matrix by viewport position and it’s converted to a valid world position by dividing by the far plane (_ProjectionParams.z). Finally, we’re calculating the snow color using XZ coordinates multiples by _SnowTexScale configurable parameter and far plane to get sane value. Phew…

Unity Snow Texture for Unity3D shader tutorial

Merging it!

It’s time to finally merge it all together!

Here we’re getting the original color and lerping from it to snowColor using snowAmount.

The final touch: let’s set _TopThreshold value to 0.6:

Voila!

Summary

Here’s a full scene result. Looking nice?

Lowpoly Township Set on the Unity Asset Store

Low Poly 3D Snow Village Unity Asset Shader

Feel free to download the shader here and use it in your project!

Scene that has been used as the example in this article comes from Lowpoly Township Set. Inspired by this particular redditor.

Debugging Web Services With Fiddler In Unity

In order to empower your Unity game with useful features like user accounts, leaderboards, achievements, and cloud saves, you are going to need a web service. Of course, you wouldn’t write one on your own, so most probably you’re thinking of using services like GameSparks or App42. If so, you should learn how to debug it.

Having a REST

If you’re not familiar with what REST is, then it’s the best time to acquire new knowledge. It’s not difficult and no, it’s not another language. It’s just an architecture, a set of rules to follow to make a good API. Thanks to REST all API services look very familiar and are easy to learn. Here’s a good place to start.

Now, when you know that REST calls are nothing else but regular HTTP requests, you may find monitoring all the http traffic between your game and web service as very useful. You may want to do this because:

  • This may be the only way to see the client-server communication
  • Client request may not be what you’ve expected it to be
  • Server response may tell you about other things than client library errors
  • Client library may have bugs that can be revealed in this way

Let’s be honest, you will encounter issues. How fast you will deal with them depends on your debugging skills. If there’s a possibility to peek into client-server communication, why you not just do it?

Wireshark?

wireshark

Most people when asked about looking into client-server communication think about Wireshark. It’s the easiest way to get hands on the full communication and while Wireshark does his job very well, I’d like to recommend something else for debugging.

Fiddler!

fiddler

Telerik Fiddler is available for free for Windows and at the time of writing of this article there’s also OS X beta version available.

What makes Fiddler so special? Especially the fact that it debugs your http traffic using build-in tools so easily. It also has a very simple user interface that is easy to understand and use. Requests and responses can be displayed as a raw text or formatted one as JSON or XML if you expect this kind of data to be in there. On top of that you can customize the requests/responses view to see the data that you’re concerned of and you do this without any trouble.

Fiddler inspectors makes debugging experience really pleasant.

Fiddler inspectors makes debugging experience really pleasant.

Do not confuse Fiddler with the packet sniffer. It does not listen to your web interface, instead it installs itself as a default system proxy. It has its pros and cons. By doing that, it can easily decrypt HTTPS communication (yeah!), but on the other side not all applications accept the default system http proxy settings.  One of these applications is…

Unity

Of course by “Unity” I also mean all apps running on Unity engine. I cannot tell for sure why Unity does not work well with Fiddler, but I know how to make it work with it. There’s a great blog post about it written by Bret Bentzinger. The steps go as follows:

Windows

  1. Make sure Unity is not running
  2. Navigate to UNITY_INSTALL_DIR\Editor\Data\Mono\etc\mono\2.0
  3. Edit machine.config file and inside <system.net> add the following:

OS X

  1. Make sure Unity is not running
  2. Locate the Unity application icon
  3. Right-click on it and choose “Show package contents”
  4. Navigate to Contents/Frameworks/mono/etc/mono/2.0
  5. Do step 3 from the Windows instructions

Important: Make sure to undo these changes after you’re done with debugging!

More about Fiddler

Did I help you make your mind? If yes, you might want to see some more learning resources about Fiddler.

Happy debugging!