C# Code Tutorial – Complete Guide

Welcome to this comprehensive and exciting tutorial where we will delve into the world of C# coding with some great examples and guided learning! If you have a curiosity for coding or a passion for game building, you’re in the right place.

What is C#?

C# is a versatile object-oriented programming language developed by Microsoft, initially to be used with their .NET framework. Its syntax is similar to C++ and Java which makes it easier to learn for those already familiar with those languages.

What is C# Used For?

In the world of game development, C# enjoys a prominent space. The reason? It’s extensively used in the Unity game engine. Whether you’re building 2D, 3D, VR or AR games, C# in Unity can be your go-to language.

Why Should I Learn C#?

Learning C# can open a world of opportunities for you. Not only does it provide you with the tools to create amazing games in Unity, but it also gives you a strong foundation in object-oriented programming. This can be beneficial in understanding other OOP languages too!

The industry demand for skilled C# developers is high, particularly in the gaming sector. Thus, gaining a strong understanding can lead to exciting job opportunities or even help you create your own indie game.

Let’s now dive into the practical aspect of C# and see it in action!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Getting Started with C# in Unity

In Unity, we use scripts to create, manipulate and control game objects. These scripts are typically written in C#. Let’s start by looking at how to create a simple script in Unity using C#.

Here’s a simple syntax on how to declare a class with the name “HelloWorld”, which is derived from the MonoBehaviour of unity:

public class HelloWorld : MonoBehaviour
{
}

However, when you create a new C# script in Unity, it will include two basic functions by default:

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {        
    }

    // Update is called once per frame
    void Update()
    {        
    }
}

Using Variables in C#

In C# programming, variables are used to store data. Here is a look at different types of variables:

public class Variables : MonoBehaviour
{
    public int myInt = 10; // Integer value.
    public float myFloat = 3.5f; // Floating point number.
    public bool myBool = true; // Boolean value.
    public string myString = "Hello, World!"; // String
}

Functions in C#

Functions, sometimes also known as methods, are a set of rules bundled together to perform a specific task. By defining a function, you can call it repeatedly in your code.

public class Functions : MonoBehaviour
{
    //A simple function to create a greeting.
    void SayHello(string name)
    {
        Debug.Log("Hello " + name);
    }

    void Start()
    {
        // Call the function with a parameter.
        SayHello("Zenva");
    }
}

Control Flow in C#

Control flow allows us to determine the flow of the execution of the codes. The most common control flows are ‘if’, ‘for’, and ‘while’

public class ControlFlow : MonoBehaviour
{
    void Start()
    {
        // If-statement
        if (1 > 0)
        {
            Debug.Log("1 is greater than 0");
        }

        // For-loop
        for (int i = 0; i < 5; i++)
        {
            Debug.Log("Loop iteration: " + i);
        }

        // While-loop
        int j = 0;
        while (j < 5)
        {
            Debug.Log("Loop iteration: " + j);
            j++;
        }
    }
}

Components in Unity

In Unity, everything from collider components to render components can be accessed using C# scripts. This way, you can interact with and control those components to make your game dynamic.

Here is a simple example of accessing components:

public class MyComponent : MonoBehaviour
{
    void Start()
    {
        // Accessing the transform component
        Transform myTransform = GetComponent();
        Debug.Log("My position is: " + myTransform.position);
    }
}

Vector Mathematics in C#

Working with vectors is a common operation in games. Unity’s Vector3 class has many in-built functions that make vector calculations simpler. Let’s demonstrate some basic vector operations.

public class VectorMath : MonoBehaviour
{
    Vector3 pointA = new Vector3(1, 2, 3);
    Vector3 pointB = new Vector3(4, 5, 6);

    void Start()
    {
        // Adding two vectors
        Vector3 result = pointA + pointB;
        Debug.Log("Addition Result: " + result);

        // Subtracting two vectors
        result = pointA - pointB;
        Debug.Log("Subtraction Result: " + result);

        // Vector Multiplication
        result = 2 * pointA;
        Debug.Log("Multiplication Result: " + result);
    }
}

Manipulating Game Objects in Unity with C#

Moving, scaling, rotating game objects – these are among the key features of game development, and yes, you can do all of them with C# in Unity. Let’s take a look at how:

public class ObjectManipulation : MonoBehaviour
{
    void Update()
    {
        // Rotate the object around its Y-axis at 1 degree per second
        transform.Rotate(0, Time.deltaTime, 0);

        // Move the object forward
        transform.Translate(0, 0, Time.deltaTime);

        // Scale the object
        transform.localScale = new Vector3(1, 2, 1);
    }
}

Learning C# for Unity game development can seem daunting at first, but with these fundamental concepts and code examples, you’re well on your way to creating amazing games.

At Zenva, we believe that learning should be a fun and rewarding experience. And what’s more rewarding than seeing the fruits of your learning come alive in a game that you’ve created from scratch? We invite you to continue your journey with us and explore the exciting world of game development with C#.

Interacting with Other Game Objects in C#

In Unity, games often involve interactions between multiple objects. Here’s how we can instantiate a new object in the scene using C#:

public GameObject myPrefab; // Assign your prefab in Inspector

void Start()
{
    // Instantiating a game object
    Instantiate(myPrefab, Vector3.zero, Quaternion.identity);
}

In many instances, we need to communicate between scripts of different objects. Let’s understand this with an example:

public class ScriptA : MonoBehaviour
{
    public void HelloWorld()
    {
        Debug.Log("Hello from ScriptA");
    }
}

public class ScriptB : MonoBehaviour
{
    void Start()
    {
        // Accessing HelloWorld function of ScriptA from ScriptB
        GetComponent<ScriptA>().HelloWorld();
    }
}

User Input in Unity

Player interaction is a key part of game development. This can be achieved through multiple ways which includes capturing mouse movements, keyboard input, touch input, etc. Here’s an example of capturing user input:

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        Debug.Log("Space key was pressed");
    }

    if(Input.GetMouseButtonDown(0))
    {
        Debug.Log("Left mouse button was clicked");
    }

    if(Input.touchCount > 0)
    {
        Debug.Log("Screen was touched");
    }
}

Working With Collections in C#

While working with a large amount of data, collections like Arrays and Lists become very handy. They store multiple variables of the same type in one place. In Unity, we often use lists and arrays to keep track of multiple game objects.

public class ArrayExample : MonoBehaviour
{
    public int[] scores = new int[] {90, 80, 70, 60};
}

public class ListExample : MonoBehaviour
{
    public List<int> scores = new List<int>() {90, 80, 70, 60};
}

Physics in Unity

Physics play a crucial role in games. Unity has a built-in physics engine that allows you to simulate real-world physics for your objects. Below is an example of adding a force to a game object:

public class PhysicsExample : MonoBehaviour
{
    public float force = 10f;

    void Start()
    {
        // Add force to the object
        GetComponent<Rigidbody>().AddForce(transform.forward * force);
    }
}

By now, you’ve got a solid introduction to C# in Unity. Remember, practice makes perfect. The more you code and experiment with these concepts, the more comfortable you’ll become at coding in C# for Unity. Happy coding!

Continuing Your Coding Journey

We firmly believe that learning is an ongoing process and it’s the same when learning to code or building games. You’ve started on a fantastic journey with C# for Unity, and there’s still a lot more to explore and master.

As the next step, we strongly recommend you to consider our comprehensive Unity Game Development Mini-Degree. This collection of courses goes beyond C# basics and brings you a profound understanding of game building using Unity. From game mechanics to audio effects to animations, the degree covers a multitude of aspects that are integral to creating immersive games. What’s more, it caters to both beginners and experienced developers, allowing you to learn at your own pace and gain real-time coding experience.

Additionally, you can check out our broad collection of Unity courses here. At Zenva, our goal is to support your learning journey from beginner to professional, with over 250 available courses in programming, game development, and AI. Keep learning, keep creating, and remember, the sky’s the limit. Happy coding!

Conclusion

As you can see, C# is more than just a programming language – it’s a critical tool for realizing your creative vision in the world of game development. With every line of code you write, every challenge you conquer, and every game you create, you are sharpening your skills and stepping closer to becoming a seasoned game developer. Remember, every journey of creation begins with a single line of code!

We encourage you to take the next leap in your game development journey with Zenva. Explore our comprehensive Unity Game Development Mini-Degree and continue your learning journey by delving into exciting aspects of game creation. Together, we can build amazing things. Let’s code the future!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.