Everyday3d
Posted on 2009-07-21

Getting started with C# for Unity3D

Getting started with C# for Unity3D

Unity3D offers a choice between 3 different programming languages: JavaScript, C# and Boo. Each of them has its pros and cons, but for me C# almost immediately came out as a clear winner.

That is because it is fully object oriented and it's syntax is similar to Java and Actionscript 3, both of which I am experienced with. However, before I started to play with Unity3D, I never wrote a single line in C#, so I had to learn it from scratch.

As you probably know C# was originally developed by Microsoft and is widely used in the .NET framework as well as in Silverlight development. It is important to understand however that learning C# for Unity3D is not the same thing as learning the .NET platform. In fact you don't have to know anything about .NET to use C# with Unity3D.

While I use all kinds of online documentation, a book is often the best companion, so I thought buying a good C# book would be in order. It turns out that the small O'Reilly C# Pocket Guide is exactly what one needs. It is absolutely unnecessary to buy a 500 page C# bible, as most of the stuff in those books is related to .NET and is not applicable to Unity3D at all.

Of course the book alone is not enough. You also need the Unity3D scripting reference. All the examples in the docs are given in Javascript only. But don't worry, they are easy to translate once you get used to.

C# is a very elegant and powerful language. It's dot-syntax is based on Java, so if you come from a Java background you'll quickly feel comfortable with it. There are a few differences though. The most striking difference is the convention to start property and method names with an uppercase letter. I guess it comes from Visual Basic. I am not a fan of this convention, but it's better to use it and have a consistent code rather than fight it.

The list of all C# features is so long, that it makes AS3 look poor in comparison. C# is really like Actionscript on steroids. I suppose the next version of Actionscript will have at least some of those implemented, so it's good to know about them. Here's a list of my favorites.

Operator overloading

This is the coolest one by far! It allows to define custom actions for common operators like +, -, * or /. The best illustration of this feature comes with vector addition. In Actionscript, to get a sum of 2 vectors you need to write something like this:

var c:Vector3D = a.add(b);

This is not very nice, and becomes almost unreadable if more than two vectors are added. In C#, thanks to the overloaded + operator it looks like this:

Vector3 c = a + b;

This is much more readable and elegant, isn't it? It goes without saying that the 3D vector implementation in Unity3D has all the operators overloaded. In case you want to do it yourself however, the implementation of operator overloading is very simple and in the above case could look something like this:

public static Vector3 operator + (a:Vector3, b:Vector3) { return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z); }

There are some simple rules: the operator function must always be static and must return an object of type it is defined for. However it can take any type of parameters. This allows to define operator overloading for adding or multiplying vectors but also for multiplying vector by a scalar or multiplying vectors by matrices. In fact this can be achieved thanks to another C# feature – method overloading.

Method overloading

Method overloading allows to define multiple methods with the same name provided that they take different parameters. It works with regular methods and with constructors as well. If there a multiple ways to create an object you can define multiple constructors to satisfy each case. As mentioned above it works with operators too.

A good example of method overloading in Unity3D API is the 'Transform.Rotate()' method. It has has been overloaded 3 times with different ways to specify a rotation:

void Rotate (Vector3 eulerAngles, Space relativeTo) void Rotate (float xAngle, float yAngle, float zAngle, Space relativeTo) void Rotate (Vector3 axis, float angle, Space relativeTo)

You can either pass a vector of angle values, three floats – one for each axis, or a single angle combined with a rotation axis. This is only logical to call it 'Rotate' every time because this is what the method does at the end.

Actionscript has default parameter values, which in some cases can simulate method overloading but they are not quite as flexible as that.

Getter/setter syntax

C# has a very concise way of declaring parameters. While in Actionscript it takes two functions – one for 'get' and one for 'set', in C# it can look like this:

public float Size { get; set; }

In this case the compiler automatically adds a private member for this property and there isn't anything else you need to do. Of course such a parameter is not very practical, so here's a more complex code, involving a public getter and private setter:

public float Area { get { return size * size; }; private set { size = Mathf.Sqrt(value) }; }

You will also notice that neither the 'function' nor the 'var' keywords do not exist in C#. In that C# closely follows Java. This is good because both these keywords are completely redundant and do not add any information to the code.

Among other interesting features I recommend to explore indexers, generic types, structures and enumerators all of which are covered in depth in the pocket guide mentioned above but also in the many online C# tutorials.

Editing C#

There are multiple editors that support C#. Microsoft offers a great and free editor called Visual C# Express Edition which features code completion, but is Windows only (obviously). For a Mac there's Mono Develop which looks very powerful, but is not very stable yet. Unfortunately the C# plugin for Eclipse is completely unstable for the moment, and I wouldn't recommend it. On the other hand, it is still in alpha so let's give it some time. Of course there's always TextMate.

Last but not least there's Unitron – the Unity3D default editor. It is not very popular among developers, and I saw people complaining about it being too basic. I don't share this opinion. While it ain't no FDT, it's pretty solid, very stable and has basic auto-completion. The trick is auto-completion is turned off by default (why?). To turn it on go to 'Preferences' and you'll find it at the bottom of the 'General' section. With that, I'm sure that Unitron is enough to get started.

Most of us know JavaScript from the browser environment. JavaScript is often the first programming language people ever used. If this is the case, you may be tempted to just use JS with Unity3D right away and not bother learning anything new. After all, as far as Unity3D is concerned, anything that can be done with C# can also be done with JavaScript.

However in the long term, C# offers better control over the code, full OOP support, strong typing and a lot satisfaction of mastering a robust programming language, so the extra effort is worth it. Plus, for a seasoned AS3 developer, mastering C# is a matter of a couple of weeks anyway, so go ahead and try it out!

UPDATE March 2010 Here's a new post about C# and Unity3D: Loading and manipulating images in Unity3D

Back
More posts

Everyday3D is a blog by Bartek Drozdz

I started Everyday3d in 2007 with a focus web development. Over the years, I wrote about technology, graphics programming, Virtual Reality and 360 photography. In 2016, I co-founded Kuula - a virtual tour software and I work on it ever since.

Recently, I post about climate, travel, art and other topics that I am curious about.