Making Unity games in pure C#
Tags: unity3d, csharp
Published: 2018-06-21 20:36:10

---
title: Making Unity games in pure C#
published: true
description: 
tags: unity, csharp
---

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](https://docs.unity3d.com/ScriptReference/). 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#](https://unity3d.com/learn/tutorials/topics/scripting/c-vs-js-syntax) 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.

![](https://cdn-images-1.medium.com/max/2000/1*_c-Ytv_IVI2Q7xJtfw0GIQ.png)

## Indentation

If you like 2 spaces indentation like me, you can go to Preferences in Visual Studio to change the editor settings

![](https://cdn-images-1.medium.com/max/2854/1*r3ihnAstxkZnDFG6qNrtvg.png)

## 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 .

![](https://cdn-images-1.medium.com/max/2894/1*QojuK8XV5FfWqs7bt-79uw.png)

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

```swift
public class Sugar {
	public GameObject makeEventSystem() {
		GameObject systemEventObject = new GameObject("EventSystem");

		EventSystem system = systemEventObject.AddComponent<EventSystem>();
		system.sendNavigationEvents = true;

		StandaloneInputModule module = systemEventObject.AddComponent<StandaloneInputModule>();
		module.horizontalAxis = "Horizontal";
		module.verticalAxis = "Vertical";
		module.submitButton = "Submit";
		module.cancelButton = "Cancel";
		module.inputActionsPerSecond = 10;
		module.repeatDelay = 0.5f;
		module.forceModuleActive = false;

		return systemEventObject;
	}
}
```

and Canvas

```swift
public GameObject makeCanvas() {
	GameObject canvasObject= new GameObject("Canvas");

	Canvas canvas = canvasObject.AddComponent<Canvas>();
	canvas.renderMode = RenderMode.WorldSpace;

	CanvasScaler scaler = canvasObject.AddComponent<CanvasScaler>();
	scaler.scaleFactor = 10.0f;
	scaler.dynamicPixelsPerUnit = 10.0f;

	GraphicRaycaster graphic = canvasObject.AddComponent<GraphicRaycaster>();

	canvasObject.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 3.0f);
	canvasObject.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 3.0f);

	return canvasObject;

}
```

and how to make some common UI elements

```swift
public GameObject makeBackground(GameObject canvasObject) {
	GameObject backgroundObject = new GameObject("Background");
	backgroundObject.AddComponent<CanvasRenderer>();

	Image image = backgroundObject.AddComponent<Image>();
	image.color = Color.green;

	backgroundObject.transform.SetParent(canvasObject.transform, false);

	return backgroundObject;
}

public GameObject makeLogo(GameObject parentObject) {
	GameObject logoObject = new GameObject("Logo");
	logoObject.AddComponent<CanvasRenderer>();

	Image image = logoObject.AddComponent<Image>();
	image.color = Color.red;

	logoObject.transform.SetParent(parentObject.transform, false);

	return logoObject;
}

public GameObject makeButton(String title, GameObject parentObject) {
	GameObject buttonObject = new GameObject(title + " Button");
	buttonObject.AddComponent<CanvasRenderer>();

	GameObject textObject = new GameObject("Text");
	textObject.AddComponent<CanvasRenderer>();

	Text text = textObject.AddComponent<Text>();
	text.text = title;

	textObject.transform.SetParent(buttonObject.transform, false);
	buttonObject.transform.SetParent(parentObject.transform, false);

	return buttonObject;
}
```

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

<iframe src="https://medium.com/media/012fa4af7350efd7b0685c909fd016bf" frameborder=0></iframe>

## Where to go from here

* [Creating UI elements from scripting](https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html): another way is to use Prefabs and Instantiate function in C# to easily reference and construct elements

* [2D Game Creation](https://unity3d.com/learn/tutorials/s/2d-game-creation): official Unity tutorials for making 2D games.

❤️ Support my apps ❤️ 

- [Push Hero - pure Swift native macOS application to test push notifications](https://onmyway133.com/pushhero)
- [PastePal - Pasteboard, note and shortcut manager](https://onmyway133.com/pastepal)
- [Quick Check - smart todo manager](https://onmyway133.com/quickcheck)
- [Alias - App and file shortcut manager](https://onmyway133.com/alias)
- [My other apps](https://onmyway133.com/apps/)

❤️❤️😇😍🤘❤️❤️