Using C# in Unity

Getting Started with C#

To begin coding in C#, you'll need a development environment that supports C# programming. The most common choice is to use Microsoft Visual Studio, an integrated development environment (IDE) specifically designed for C# development. Visual Studio provides a rich set of tools and features to help you write, debug, and deploy your C# applications. Visual Studio comes with the installation of Unity.
 
Open up your 2D Unity Project. There will be a project section on the bottom. On your project, right-click and add a new folder, name it scripts. Then right-click and create a C# Script in your folder. Click on the file named “NewBehavior”. Visual Studio will then open up. On new behavior you can see the code before.
 
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewBehaviourScript : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
 
Now let’s explain this code:

What are we using?

using System.Collections; using System.Collections.Generic; using UnityEngine;
 
In this section, we are importing the necessary namespaces. The System.Collections and System.Collections.Generic namespaces provide classes for working with collections, such as lists and arrays. The UnityEngine namespace contains the core Unity engine functionality.

MonoBehavior?

public class NewBehaviourScript : MonoBehaviour
 
Here, we define a new class called NewBehaviourScript that inherits from MonoBehaviour. In Unity, scripts that control game objects are typically derived from MonoBehaviour. This class represents a behavior that can be attached to a game object and contains methods that are automatically called by the Unity engine.

Start

// Start is called before the first frame update void Start() { }
 
The Start() method is a Unity callback function that is called once when the script is enabled and before the first frame is rendered. You can put initialization code or setup logic inside this method.

Update

// Update is called once per frame void Update() { }
 
The Update() method is another Unity callback function that is called every frame. It's where you put code that needs to be executed continuously, such as player input handling, movement updates, or other real-time actions.
There are other in-built methods, such as OnCollisionEnter(Collision) and OnCollisionExit(Collision), and to use these we must declare them individually. But those methods can be dealt with on a case-by-case basis. For now, though, these are the basics.