JetBrains Rider, an alternative IDE to Visual Studio for Unity C# Development

JetBrains Rider: An Alternative to Visual Studio

For quite a long time, Unity installer came with a custom MonoDevelop distribution to assist Unity developers with starting with game development. At that time, it was the only available option for many, since other solutions were simply too expensive. Visual Studio Community was then introduced, and almost immediately it became the default Unity C# IDE, but only on the Windows operating system family. It seems like quite soon we will have another player on the market and its name is JetBrains Rider.

.NET enslaved by Windows

It’s not surprising that the language created by Microsoft works best on Windows operating system family. It seems that even Microsoft is surprised by how .NET got so popular these days. It’s a bit of a problem, because today we’re entering a new era in which Windows is no longer a dominant operating system in the world and .NET is widely used on variety of platforms thanks to Unity. If Microsoft wants to keep .NET position and profit out of development tools, .NET must become a cross-platform framework for real.

The first step of becoming more open to multiple platforms was introducing .NET Core (wikipedia) – the first open-sourced .NET implementation. Then Microsoft introduced Visual Studio Code – the first editor with “Visual Studio” in name that works on MacOSX and Linux. Still Visual Studio Code is “only” a GitHub Atom fork. It’s a great editor, but it’s nothing when compared with original Visual Studio IDE running on Windows with ReSharper onboard. Speaking of which…

There’s a new player in the game: JetBrains Rider

There’s a market gap for sure – more and more developers tend to use Mac OS X or Linux as their development platform and beside Visual Studio Code and MonoDevelop (which is good, but not so great) there was nothing worth considering until recently.

JetBrains is a Czechia based company known for the creation of a great Visual Studio extension called ReSharper, and IntelliJ IDEA (IDE for Java developers). It seems like they’ve recently decided to merge those two.

JetBrains Rider is a cross-platform .NET IDE based on the IntelliJ platform and ReSharper. If you don’t know either one of those, then consider this as a great opportunity because learning these two tools will change the way you work with your code forever. Do I need to tell that it will increase your productivity? Yes, it’s a buzz-word, but it’s true! What is more important, it will make your work easier and you – happier.

How valuable is your time?

Do you value your time? How much time do you spend on writing easy but bloated code and how much on focusing on problems that matter? ReSharper is a tool that helps you to get through the parts of the code that are not requiring too much of your brainpower. It consist of powerful generator and refactoring methods that will assist you on demand. It also includes code analyser that makes sure you won’t make any simple-to-prevent mistakes. Besides that, it just tries to be smart and friendly to a developer.

Rider comes with native Unity plugin! It does not only make it aware of *.meta files, but also know MonoBehaviour specific methods like Update(). Thanks to it you will see a code-completion of these methods and you won’t be seeing any warnings about unused functions.

It’s even aware of Unity-specific optimizations like tag-comparing:

And maybe it’s not that important, but it also shows how Rider developers are getting into details – colouring of Color struct constructor:

Yeah, your guess is right! It shows you the actual defined color!

I won’t make a complete list of ReSharper features, because there’s just too many of them. Instead, please browse the documentation. There’s a lot of great and simple to understand examples out there.

Still, it’s important to mention that Rider, by contrast to Visual Studio Community and Visual Studio Code, is not free. Actually, it is distributed via Early Access Program which now costs nothing, but it’s justified to believe that Rider will be using a subscription payment model. For many people this information would be a no-go, but consider whether it is worth it – it can increase your productivity (in my opinion quite a lot, if you get to know it well).

But I’m happy with my Visual Studio on Windows!

I’m also a satisfied Visual Studio user on Windows. Why changing it then? The reason may be quite simple, take me for example. I’m working on Windows about 50% of time. Rest of it I spend on my MacBook and Linux Mint. On all three I sometimes need to do something in Unity. The real pain is that I have to use totally different IDE on all three platforms since Visual Studio Code for some reason does not play well with Linux (some strange mono issues) and I had to use MonoDevelop there. I’m really looking into Rider to get out from EAP to use it constantly on all of my 3 development platforms. And even now, while it is still in early stage, it works really, really well! Yet, if this scenario doesn’t fit you at all, I still encourage you to try it!

Conclusion

Rider is a fresh approach to .NET development. It focuses on developer’s productivity, happiness and it is aware of current market trends, which makes it an interesting alternative to Visual Studio.

JetBrains reader can be downloaded for free from its home page. Each version has a expiration period of one month. New versions are released at least once a month so until Rider is still in development, you will be able to work with it without any costs.

I strongly encourage you to learn as much shortcuts as you can – this IDE has been created for those who favor keyboard over mouse. If you don’t know the shortcut that you’re looking for, try hovering over an option to see a tooltip that often will tell you wanted key combination or try pressing shift twice to open Search Everywhere popup. It allows you to search through all of the Rider actions.

MonoBehaviour call optimization for Unity developers

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/

 

Computer Programming Code

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!