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.

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!

Coroutines in Unity Part 3

Coroutines in Unity – Encapsulating with Promises [Part 3]

 

In the last part of the series we’re going to build a real example of a REST API Interface using Unity’s Coroutines as an internal web requests tool and Promises as an encapsulation layer. We’re going to use the fake REST API service available for everyone to test their services on. It’s a simple API that implements the classic user to-do lists, posts & comments section as well as the album & photos scenario. Very useful if you’re building your own front-end but don’t have your own running server just yet.

NOTE: This tutorial is a bit more advanced and it won’t teach you REST backend theory or JSON serialization. It also assumes you’re already familiar with the RSG Promises we’ve covered in Part 2.

The project

Our project is going to be based around the user to-do lists. The main feature is simple: it’ll take a username as input and provide a list of tasks associated with that user. The application is going to get a list of all the users, find the searched username in it and if that user exists it will then grab all the tasks. Ideally you’d want the user searching to be done server-side, but for the sake of this example let’s say someone hadn’t thought it through and left you to do your job.

For JSON deserialization we’re using the popular JSON .NET framework. If your project is going to be cross-platform you should take a look at JSON.NET for Unity, which uses the same namespace and structure so it can easily be used as a drop-in replacement.

We’re going to work with Unity 5.4.0f3. You can download the .unitypackage here with a complete project and all the necessary plugins. Let’s dive into it.

The project features a Plugins directory, Scenes directory with the single example scene as well as Scripts directory, where the whole codebase sits. The code is structured as follows:

devenv_2016-08-24_11-09-12

Let’s start from the top.

The Models

The Models directory is where the data models’ classes are. They’re essentially the classes with properties mapped to JSON object keys. For example our JSON of a single Task object looks like this:

The associated Model class is then being implemented in the following way:

As you can see, JSON .NET allows for an extremely easy mapping using the JsonProperty attribute. Actually, you can skip these entirely if the property name matches the JSON key. Personally I prefer camelCase in my JSONs and PascalCase in my properties. Keep in mind that for AOT platforms you should use JSON .NET for Unity or use regular fields. Refer to the documentation for more information.

The User model is a stripped model as the jsonplaceholder returns a much bigger JSON, but for the purpose of this example we will not implement all the properties.

Promises as a service interface

Let’s say you’re working on a REST API for a month only to find out that management of your company decided to move to Websocket. Or perhaps you’re ahead of your backend department and want to test new features on your own without the need of using a real server. To remedy this it’s a good idea to implement the Factory pattern which let you choose the exact implementation of your service (APIServiceFactory) by encapsulating a common interface for all of them (IAPIService). The interface is using Promises as the abstraction layer so it’s very easy to use.

To search users and list their tasks we only need two functions:

If you’re going to need another API implementation in the future all you have to do is create a new class that will implement these two methods. The instantiation is done via the factory and the provided config (IClientConfig and ClientConfig):

RestAPIService

The REST API implementation uses the Unity’s Coroutines and the UnityWebRequest class under the hood. Because of that, the factory creates a GameObject and attaches the RestAPIService class, which also extends the MonoBehaviour. This lets us encapsulate the coroutines even further – you’ll be able to use the service in all of the classes, because the interface deals with Promises only. For example, getting the user tasks is done like so:

Notice how easily we control the output with promise.Resolve() and promise.Reject().

TestAPIService

The test implementation is just an example of what you can do. It returns objects without any external calls, but you could also use it as a room to test your JSON deserialization without launching a real server. The bottom line is that this should be the space to mess around with no worries that you’re hard-coding some test scenarios which need to be commented out later. All you have to do is change the config to the real service and you’re done.

So for example, if you’d like to test how your tasks` UI look, but don’t have the tasks functionality done server-side just yet, simply implement the test service and the GetUserTasks() method to return a bunch of test objects:

Notice that you can resolve promises instantly when needed.

The result

The payoff is the example test scene and the MainScreenController class which utilizes the interface. First, it initializes the service using the Factory:

As mentioned earlier, changing to Test implementation is as simple as swapping that APIType property in the config. The UI consists of a single input field where you type in the username and a button to get all the user tasks. Using the common interface it couldn’t be any simpler:

2016-08-24_10-46-14

Summary

And at last we come to an end of the series. Again, the final project can be downloaded as the .unitypackage here. In conclusion Promises prove to be a great way to abstract your code from Unity specific Coroutines. They can also be used in many different cases and are an elegant way to create clean interfaces. We hope you’ll enjoy them as much as we do. If you have any questions about the series or the example project, feel free to leave a comment in the section below.