How to make Unity games in pure C#
Issue #275
Original post https://codeburst.io/making-unity-games-in-pure-c-2b1723cdc71f
As an iOS engineers, I ditched Storyboard to avoid all possible hassles and write UI components in pure Swift code. I did XAML in Visual Studio for Windows Phone apps and XML in Android Studio for Android apps some time ago, and I had good experience. However since I’m used to writing things in code, I like to do the same for Unity games, although the Unity editor and simulator are pretty good. Besides being comfortable declaring things in code, I find that code is easy to diff and organise. I also learn more how components work, because in Unity editor, most of important the components and properties are already wired and set up for us, so there’s some very obvious things that we don’t know.
All the things we can do in the editor, we can express in code. Things like setting up components, transform anchor, animation, sound, … are all feasible in code and you only need to using the correct namespace. There’s lots of info at Welcome to the Unity Scripting Reference. Unity 2018 has Visual Studio Community so that’s pretty comfortable to write code.
Javascript and C
I would be extremely happy if Unity supports Kotlin or Swift, but for now only Javascript and C# are supported. I’m also a huge fan of pure Javascript, but I choose C# because of type safety, and also because C# was the language I studied at university for XNA and ASP.NET projects.
Indentation
If you like 2 spaces indentation like me, you can go to Preferences in Visual Studio to change the editor settings
GameObject and Canvas
In the Unity editor, try dragging an arbitrary UI element onto the screen, you can see that a Canvas and EventSystem are also created. These are GameObject that has a bunch of predefined Component .
If we were to write this in code, we just need to follow the what is on the screen. In the beginning, we must use the editor to learn objects and properties, but later if we are familiar with Unity and its many GameObject , we can just code. Bear with me, it can be a hassle with code at first, but you surely learn a lot.
I usually organise reusable code into files, let’s create a C# file and name it Sugar . For EventSystemand UI we need UnityEngine.EventSystems and using UnityEngine.UI namespaces.
Here’s how to create EventSystem
1 | public class Sugar { |
and Canvas
1 | public GameObject makeCanvas() { |
and how to make some common UI elements
1 | public GameObject makeBackground(GameObject canvasObject) { |
Now create an empty GameObject in your Scene and add a Script component to this GameObject . You can reference code in your Sugar.cs without any problem
1 | public class MenuScript : MonoBehaviour { |
Where to go from here
Creating UI elements from scripting: another way is to use Prefabs and Instantiate function in C# to easily reference and construct elements
2D Game Creation: official Unity tutorials for making 2D games.