Everyday 3D

Creative use of technology // A blog about 3D Flash and Actionscript by Bartek Drozdz

Getting started with C# for Unity3D

C#

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:

Actionscript:
  1. 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:

C#:
  1. 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:

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

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:

C#:
  1. void Rotate (Vector3 eulerAngles, Space relativeTo)
  2. void Rotate (float xAngle, float yAngle, float zAngle, Space relativeTo)
  3. 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:

C#:
  1. 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:

C#:
  1. public float Area {
  2.     get { return size * size; };
  3.     private set { size = Mathf.Sqrt(value) };
  4. }

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
(more coming)

Categories: Actionscript 3, CSharp, Unity3d

comments RSS

32 Comments

  1. Yeah C# is best language I know and damn how I lack many things in AS3 :( Proper generics, overloading, explicit interfaces… With them building complex solutions would have been SO much easier. Also Reflection + runtime compiler are nice in some special cases, but I am not shore Unity has runtime compiler (but it has reflection I presume).

    I accentually wonder if we will see Unity based websites (or rather promotional pages) anytime soon. Is unity even possible to use for this? Or it is just games?

  2. Wellp, i’m convinced.
    Gonna spend this weekend messing around, I was deterred because of the high production cost of creating a Unity3D game so i felt it was not REALLY worth the time.

    However, now i’ll just learn it to learn another language, which is always great.

    Excellent post

  3. I spent three months last winter mostly coding in c# and it is definitely a very nice language. I’ve been planning a series of blog posts on “C# for as3 developers” but haven’t got around to it yet.

    There are lots of similarities but lots of extra niceities in C#. I was using .net (the framework isn’t nearly as nice as the language) and visual studio but I may look into Unity – it sounds really interesting.

    Visual Studio is a really nice IDE if you can find a windows machine to run it on – the intellisense is better even than FDT is for as3. Some things that I liked from c# include: implicitly typed local vars and LINQ. As already mentioned, generics, method overloading and reflection are also really good…

  4. Adam

    C# iss based on Windows, I prefer Javascript, but I like C++ more. :-)

  5. [...] 原文出处:Getting started with C# for Unity3D 原文作者:EveryDayFlash [...]

  6. C# has really evolved nicely. In Unity3D I recommend it as well mostly because when you get to the networking and sockets portion of your game using TCP or UDP directly in the browser, it needs to be C#. But I have had projects with gamecomponent scripts written in C#, Javascript or Boo and it all runs the same on mono .net implementation.

    I am getting to the point now where I also use the Unity3D IDE a bit less and actually apply game components via code which makes for very fast development in Unity3D for new projects and your components are very reusable.

    Most flash programmers that haven’t been .net developers or c#/java/C/C++ type developers will be comfortable with the Javascript version that Unity3D includes and be almost as productive as hardcore programmers at least in game logic though. I absolutely love the mono .net framework, thank Miguel de Icaza when you can: http://tirania.org/blog/

  7. marjan

    Very interesting.

    But don´t you think that unitys implementation of avascript is far more like Actionscript? You con almost copy whole code blocks from AS and get it to run.

    Unity Javascript seems closer to AS in general. When you write a methode in js you can write:
    public Stop(obj : System.Object, name : string ) : void

    instead of c#
    public void Stop(System.Object obj, string name)

    Of course there are some nasty pitfalls here and there, for example in Arrays. A lot of Array Methods ar non present. Or do while(). There is only a while() as i remember.

    I don´t know how that is handled i c#.

    Furthermore, the underlying mono seems to be more powerful then unity javascript.
    A small example is the varuable type uint. While working in unitron, uint is not colored, which made me think it doesn´t exist. In unitys dokumentation it is also not mentioned.
    But it actually works. There seem to be a lot of these things but i have no idea where to look that up.

    Thanks for the autocompletion tip!

  8. Nice article,I’m just starting with C# and Unity, and tip for the book is a big help for me!Thx

  9. [...] Getting started with C# for Unity3D [...]

  10. Hi,

    I’m not sure if somebody has mentioned this before. but if you’re looking for a C# editor, the Visual Studio C# Express Edition might work. and It’s free. I know there’re a couple of nice IDEs but I don’t remember the name of them.

    Herberth

  11. Thanks for this article – I was wondering about a book that would be appropriate for learning C# for Unity. But would you recommend the book for people (like me) who have ZERO Object-oriented programming experience? I know enough Javascript to sometimes recognize copy/paste errors when stealing code to use on websites – which is to say, practically none. Would the O’Reilly guide be enough for me?

  12. @Godheval Good question. I think if you want to learn OOP from scratch that book might not actually be the best choice. I learned OOP many years ago from a wonderful book called “Thinking in Java”(http://www.mindview.net/Books/TIJ/)

    As its title suggests it’s a book on Java programming, but the OOP concepts are the same everywhere. I guess today there are many other good books out there about object oriented programming, some for AS3 and some for c# but I can’t recommend any since I haven’t read them.

  13. And one more question… If I’m completely new to OOP, would you still recommend C# over Javascript? The Unity forums seem to be split right down the middle regarding which is best. I was thinking JS for two reasons:

    1. I can use it for web design outside of Unity
    2. The Unity reference guides and wiki and the one book I found on Unity (Unity Game Development Essentials by Will Goldstone) all use JS.

    As for C#, I was thinking that it would be more useful in general, rather than just for web-based stuff.

    Thanks for the help…

  14. @Godheval The syntax of JS is a subset of C# (kinda) If you take the time to learn a full featured OOP language like C# you won’t have any problem in understanding JS (you will also then see why JS is bad). Furthrmore, you will be able to pick up Java or AS3 relatively easily too because all these OOP languages are very similar.

    On the other hand there’s nothing to gain by limiting yourself to JS. It’s a lousy programming language and using it too often leads to bad coding habits :)

    If you go through Will’s book, translating all the code from JS into C# is actually a very good exercise.

  15. The people who suggest JS are those who aren’t or weren’t experienced programmers when they started. It sounds like JS was made specifically for people who weren’t ready for “REAL” programming (like Java). Is this why you say JS is a lousy language? Because it requires less “manual” programming (not even sure what that means)? I was also looking at this:

    http://unity3d.com/support/documentation/ScriptReference/index.Writing_Scripts_in_Csharp.html

    I mean, if C# is the better language, why is all the documentation in JS?

  16. @Godheval JS is OK for design oriented people that want to use scripting occasionally for smaller tasks. This is perfectly possible with Unity3D since a lot can be done without a single line of code. That is why all the examples are in JS – to make them available for a larger group of users.

    What I meant is: if you want to learn Object Oriented Programming JS is not a good choice. You need to consider if you need to/want to teach yourself OOP or not (ex. if you are thinking about a career as a developer, many employers will require OOP). So, take a second to think about it. If the answer is ‘yes’, learn C# if not, stick with JS.

  17. [...] a look at learning C# for Unity. It’s not that different to AS3 really, and in many ways it’s much more powerful than [...]

  18. [...] rather than the standard Unity JavaScript. I chose to try and learn C# after reading this post on EverydayFlash which had recommended it. It took a little getting used to but it was definitely worth learning, [...]

  19. NAZ

    What is that book called

  20. achmad

    c# is best as far from my experience even compare to c++, c# isn’t far behind as people guest, and the sole reason i’ve choose unity is the support of c#..great works guys!!!

  21. C# is definitely a nice language and was designed to overcome most of the pitfalls/shortcomings of older languages like C++ and C.

    Personally, even though I love C#, sometimes I’m lazy and I like implicit and dynamic typing that JS offers. If I’m doing anything complicated that requires use of OOP techniques though – or anything that *may* be hard to debug down the road I always use C#.

  22. GabeM

    O’Reilly also offers the same pocket guide for C# 4.0. Should I still purchase this 3.0 version? I can’t figure out which version Unity is using. Maybe either book will do?

  23. @GabeM either will do. At the time I published this post 3 was the latest version, but Unity only supported version 2. They are all backwards compatible of course, so it’s just that you won’t be able to use some latest features, otherwise the book is ok.

  24. Adil Patel

    I HAAAAATE C#!!!!!! C++ and objective-c ftw!!!!!!!!!!!!!!!!!!!!!!

  25. Thanks Adil for this in-depth analysis :)

  26. You mentioned that the script reference is only in javascript. How wrong! every example can be changed to js, c#, or boo simply by clicking the dropdown in the top-right of each code example. I understand what your saying about translating, but it could save you so much time.

  27. @jasonM Thanks! Back when I was writing the article the docs have been in JS only, since then they added the other languages. I need to update the post :)

  28. Game Dev Wanted

    Nice post. Sorry for the off-topic but I struggle to find skilled coders for a browser based 3D game. I am wondering whether there is anybody here who might want to work with us. We need some performance optimization and coders able to handle Javascript or C#… Please mail to nyce-design@gmx.net once you feel like making some money :)

  29. hassan

    thanks for your post
    but i have question:
    is there any book or tutorial to learn C# just for unity?

  30. I have a solid base in C/C++ and some experience with Java. Logicly i will use C# in this package. But it’s a betther option build in Unity3d becose is strongly typed and object oriented.

  31. [...] 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: Getting started with C# for Unity3D – Everyday 3D [...]

  32. DAud

    Hi! There is a typo in the operator overloading section:

    public static Vector3 operator + (a:Vector3, b:Vector3) {

    is rather

    public static Vector3 operator + (Vector3 a, Vector3 b) {

    I guess you used ActionScript syntax there?



  • FATC2011


  • FITC2011


  • FITC2010


  • FITC2010