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!

Dream Big, Start Small

What motivates you to go on with your ideas? Would you like to build a game that will be the next big thing in the industry? Who wouldn’t!

A path to success

People ought not to hear and talk about failures. Instead of it we discuss successful stories about how a small indie developer has made a game that brought him thousands dollars of income per day. Some of these ideas seem to be so simple that you may think to yourself “why I did not come with such an idea?!”. I will tell you why – it’s nearly impossible to be successful at very first attempt, you have to fail first, fail often, fail miserably, fail hard. You will never know how to build a successful product until you learn how to not create one.

Not very heartening vision, isn’t it? At first, I didn’t want to believe it. I had a strong faith in each of my projects even if almost all of them were failed attempts to create something bigger. I’m a very stubborn person, so even after a series of big failures, I kept going. But sometimes I was seriously thinking about giving up. I’d like to give you a piece of advise on how to deal with failures and how to reach out for a success much quicker than I did. I hope that your understanding of what a failure is will change, because believe me – it’s not that bad.

Start small

If you’re playing any game for the first time, you need to learn how to play it. There can be a tutorial, or a set of easily understandable stages where you are learning the mechanics. Then, it’s all about exercising to get through more difficult stages. From time to time, there can be a boss fight and the final boss at the end of the game. Final boss should be something that will test everything you’ve learned while playing the game. Beating him gives a great satisfaction that your hard work finally brought you to that very point.

With some exceptions you wouldn’t go for a final boss fight right after starting to play. You know that you do not have enough experience and you will fail. So why would you then go and try to create an epic game with large world and extraordinary story-telling if you don’t know how to create a simple puzzle game? Maybe because you do not realize that this is your personal final boss.

Think of a gaming industry as your newly bought game. Even if you feel that you know how to play it, assume that you don’t – that’s a safe assumption that can be easily verified in a short period of time. Now start small. Put your plans about big and wonderful games aside. Think of something really small, like Tetris or Breakout. Make a list of ideas and choose one that you believe would need the smallest amount of time to achieve. This is where you want to start!

Don’t get discouraged by that! Small and simple games can be interesting and exciting. Just think of it as of an exercise about creating a good game mechanics out of a simple idea. Great AAA games are filled up with a bunch of smaller game mechanics, even if you might not realize that yet. A game theory may be something that you need.

Don’t worry about the game marketing at the beginning. Even if you create a good game and there will be nobody to play it, make more games. Cross-promote it, talk about your creations on Reddit. If it is good, you will surely get some attention. Besides attention, you will also get some feedback. A word about feedback – wait for opinions to repeat itself. If you will hear several opinions about the same thing, this means that it may be really important thing to take care of. Otherwise, don’t waste your time.

Dream big

When you will decide to start small, there will alwaysbe a dream that will have to wait for its time to come. But how could you know when the time is right? Trust me, you will! Until then, you will get a plenty of experience, you will know your enemy well and most probably – you won’t be alone. You may get to know a bunch of experienced people who saw you going forward step by step and will be willing to help you with your dream.

Do you know somebody that is so full of life that it affects all the people around her or him? Being a positive person significantly changes your surroundings. You will attract people who are thinking similar, change minds of those who are uncertain and scare off toxic people. The same applies to you – if you’re working hard with belief that someday you will fulfill your dream – you will attract people who are similar to you.

Be prepared that your dream may evolve to something else. As you will be discovering the market better and you will understand more and more what makes a game successful, you may alter part of your idea. That’s a good thing, because by doing that you’re increases the chances of your big dream becoming successful.

What if your big dream will fail… again? Until now you surely have learned that a failure is not the end of the road and even a failed project can be continued. Sometimes it just needs a little push to a different direction, a fresh idea or even a restart.

Keep believing in your dreams. Be prepared for a failure and learn why it happened. Make sure to fail a little less with each new project. Repeat the process and one day you will fulfill your dreams. This will be your final boss and the reward for everything you’ve learned on the road so far.

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/

 

7 Things to Remember When Working in a Team

Whether you are working in a team or alone, you should know how to efficiently work on a project with other people. It will not only make working on a single project with someone a lot easier, but also improve your coding style and project management skills significantly. It’s nothing to be afraid of, really! I’d like to explain in a few steps what are the most important aspects of working in teams.

1. Organize your project well

Before progressing any further you must make sure that your project is well-organized. It’s an important requirement because unorganized project is very difficult to maintain. It’s not impossible to work on such project by all means, but each time you will be forced to work on it, you may feel an unstoppable desire to murder someone in your near proximity. And this feeling will get worse as the project will grow.

You can learn how to keep your project organized from one of our previous blog posts.

2. Setup an issue tracker

If you aren’t using one already then I am sure that you’ve heard at least about Jira, Redmine, Trac or Mantis. In fact, there are a lot of these and you may have a serious problem with deciding which one to choose. From my experience there’s no solution that can be called “the best one”. All of these has some pros and cons. I strongly encourage you to check at least 3 of them before decidingwhich one will be good enough for your needs. Keep in mind that you will learn what you really need only after a few months of working with any of it.

Why issue tracking is that important? When working in a team, good communication is a key. Humans are lazy and forgetful creatures. If you tell someone that he/she has to do something, he/she remembers that task clearly until tons of similar tasks fall out from the sky. You have to accept that simple fact. Also don’t rely on your own memory – it has been proven that the need of remembering a lot of things significantly increases your stress.

3. Switch your projects to force-text serialization method

It’s obvious but can be often forgotten. Unity is using binary serialization method for its assets by default (hey, Unity guys! Who told you that would be a good idea?). This simply means that if two people will change a scene, animation setting or a prefab at the same time, one person will have to give up his changes because of a conflict. The situation is similat to the one in which two guys dating the same girl. One of them sooner or later will have to give up (let’s not talk about alternatives, shall we?).

Force-text serialization can be enabled in the Edit -> Project Settings -> Editor:

You don’t need to confirm anything. Unity will perform re-serialization of your assets immediately.

4. Agree on a common coding style

Be ready for a big fight – programmers don’t like to change their habits. But you and your colleagues still need to do it, otherwise it will cause a lot of nasty conflicts on code merges. Also, you have to decide if your source files should use tabs or spaces for code indentation. You may look for something like an official or community style guide for a specific language. There’s one for C#  that you may find useful. You don’t have to blindly follow if you don’t agree with some parts of it, but when there will be a disagreement within your team, it may be a good source of possible solution.

Remember to not force any decisions on your team if there’s a strong defiance on that matter. If you want them to give everything they got to your project, you have to make them love working on it, not hate it!

5. Agree on asset changes policy

Some assets can be hard to merge even if you switch the serialization mode to text. It may be necessary to decide on a policy on how and when communicate that someone is about to edit an asset. Some VCS like Perforce or PlasticSCM offer a feature called exclusive checkout. It means that all files are read-only until someone will decide to edit it. If the second person tries to edit that file in the same time, he/she will receive a warning that this file is being checked out by someone else.

You may also want to take more human-like approach. I knew one company that had a magnetic table with post-it notes on it. Each note had a scene name written on it. If someone decided to edit a scene, he or she took matching note to his/her desk so anyone else knew that this scene was currently being changed.

6. Communicate often, but watch for interruptions

Talk often with your team about what they did and what they are about to do. Do it every morning if possible and make it short. Discuss about possible issues and how to solve them, if needed.

Talk with your teammates often if you need to, but watch out for interrupting their work. Avoid calling them or speaking to them personally without earlier notice. If you do that, you decline their right to react whenever it suits them. You make them immediately lost the context of the work they were doing and to focus on your thing – it’s a very selfish thing to do. Even if you’re in a hurry, try to notify them using an email message or IM first.

Choose communication software that allows to freely configure its verbosity level. Some people don’t mind to be interrupted, some does. Nearly every e-mail client allow to freely configure notifications level so if you want to talk about something and you’re not in a hurry, use e-mails. Some things cannot wait for too long, so you need Instant Messaging of some sort. I strongly recommend you to try Slack. Slack highly respects everybody’s right to not be interrupted and gives an option to allow interruption in really important matters. Slack also allows your team to create channels. Channel is a place when two or more people can discuss with each other about one specific matter.

7. Try Unity Collaborate

Not so long ago Unity announced their new service called Unity Collaborate. It’s worth trying because it directly targets Unity developers and the client is working within the Unity editor itself.

We’ve never been using Unity Collaborate (it’s still in beta stage), but it promises to solve issues with data merging and staying in sync with your teammates. It’s worth checking and you can try it for free.

What else?

There are no two identical projects and two teams will never be the same. You should keep your eyes and mind open, and watch for any issues your team encounters that are worth solving. Not all issues can be solved easily and many project directors make a mistake with solving an issue with a solution that makes it even worse. Trying is not a sin, but not admitting we made a mistake and regressing in work that has already been done unfortunately is.

You don’t need that comment!

Let’s talk about programming. Since you’re a Unity developer then most probably you had to do some programming, unless you use Playmaker or something similar. As a programmer you most probably want your code to be as readable as possible, because sooner or later you will have to work on it knowing why you’ve done something in a particular way. What is your method of making your code more readable? Do you use in-code comments? If yes, you’re doing it terribly wrong.

Why comments are bad

You may now think of me as of an idealist. Thinking of a world without conflicts, religion, etc. Well, it’s nothing like that. Every source code requires more or less comments, but in most cases, when you may want to write one, most probably there’s a better solution.

Why do I state that using comments is bad?

Comments can get quickly outdated

Consider this piece of code:

And let’s say someone will refactor it:

The person who did the refactoring replaced 60 seconds with PlayTime field and then made it 120. It’s a common “mistake” to leave the comment. Even if the comment would be updated, anyone who will change the PlayTime value won’t be aware of a comment in Update() function that is now lying to us.

Comments need to be read along with the code

Isn’t this a purpose of comments existence? Well it actually it is, but if there’s a comment then it means that reader needs more time to get through the code because he or she needs to analyze code and all the comments. It’s not only the matter of how much there’s to read – code that needs a comment can be understood only when reader can get understanding of a comment – so there’s as twice as much things to analyze.

Now I’d like to show you some real scenarios in which comments were used, as well as how it can be improved and why.

Use meaningful variable names

Something so obvious, yet frequently ignored. How often did you stumble upon variable names like abx2, etc.? Let’s take this code example:

First of all you should know that using short variable names won’t make your application faster. It only will make your code less readable. Always remember to use meaningful variable names. “Meaningful” does not mean long, so if you want to use a short version of variable name, you are allowed to do so, provided that it can be easily decoded (pointer -> ptr, texture -> tex). Using too long variable names can easily backfire with code that is too bloated, so you have to make compromises.

Note that we not longer need the comment because playerToEnemyDist variable name tells us enough about what we’re doing in that line.

One more note about variable names: for loops are frequently using a counter variable. It’s perfectly legal to use “i” or “j” as a counter name since it is widely used style of naming. The same applies for “x”, “y” and “z” while we’re making operations on coordinates.

Do not use magic numbers

“Magic” numbers are numerical values that exists inside methods and it may be difficult to know why these numbers are set in a particular way. Magic numbers should be extracted into variables, fields or even class constants with meaningful names.

Do not explain ifs

If you have an if statement and it may be not clear what it does and why, you may be temped to make a comment to that statement. Before you do, think of extracting your if () condition (what’s inside) into a meaningfully-named method.

Please note two things:

  1. By extracting if condition we could move distance calculations into a separate method so Update() function has much less code to read now.
  2. EnemyIsNearPlayer() function name is self-descriptive. We do not need a comment here.

Watch out for function parameters

See this code?

How you can tell if the poison is a secondary attack without a comment? Well, you cannot. This scenario is a good example where a comment is really needed. Still, if enemy’s class is something that you can refactor, consider using a struct instead of raw parameters:

So our code may finally look like this:

Summary

At first glance it may look like  producing more code instead of using comments for much simpler code, but trust me – this will greatly make you and your colleagues’ life much better in the long run.

Still, if you feel that a comment is really needed and there’s nothing else to do – go ahead! There are situations where you cannot do much about it. Yet remember that the information in your comments may someday become outdated, so keep it simple and safe.