C# Example Tutorial – Complete Guide

Welcome to our comprehensive guide on game development with C#. Whether you’re an experienced coder looking for a fresh perspective or a coding newbie stepping into the fascinating world of game development, we’ve got you covered.

In this tutorial, we’ll help you explore the depths of C#, one of the most highly-regarded programming languages in game development. By creating simple game mechanics from scratch, you’ll gain a robust understanding of C# and how effective it can be for your projects.

What is C#?

C# (pronounced “C Sharp”) is a multi-paradigm programming language designed by Microsoft. It offers simplicity, powerful features, and a strong type system, making it a popular choice for many fields, including game development.

Why Should I Learn C#?

C# is the main language used in Unity, one of the most popular gaming engines in the game development world. Learning C# will strengthen your fundamental programming skills, as well as equip you with the knowledge you need to create amazing games.

Furthermore, C# can be utilized beyond game mechanics—the language is also great for building AI systems, databases and more.

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

Understanding Basic Syntax in C#

Before diving into coding games, let’s familiarize ourselves with the fundamental syntax of C#. This will pave the way for smoother game development later on.

Writing the Main Function:

The main function serves as the entry point for any C# application.

class Program
{
    static void Main(string[] args)
    {
        
    }
}

Variable Declaration:

In C#, variables must be declared with their types before they can be used.

int myScore = 100;
string playerName = "Zenva";

Operations:

Regular mathematical operations can be carried out in C# using the usual symbols.

int x = 10;
int y = 5;
int z = x + y; // z would be 15

If Statements:

C# also includes conditional ‘if’ statements, very useful when creating different outcomes based on various game states.

if (score > 100) 
{
    Console.WriteLine("You've won the game!");
}

Creating Game Mechanics in C#

With a basic understanding of C# syntax, we can now delve into creating some simple game mechanics. We’ll explore some key fundamentals that underline most games, such as character interactions and game controls.

Player Jump:

The following code indicates that a player will jump when the space bar is pressed.

void Update(){
    if(Input.GetKeyDown(KeyCode.Space)){
        Jump();
    }
}

void Jump(){
    //Your Jump code here
}

Technical explanation: The Update() function is called once per frame. Inside it, we’re checking if the Space bar has been pressed. If it has, then we are calling the function Jump().

Making an object move left or right is just as simple:

void Update(){
    if(Input.GetKey(KeyCode.A)){
        MoveLeft();
    }
    if(Input.GetKey(KeyCode.D)){
        MoveRight();
    }
}

void MoveLeft(){
    //Your move left code here
}

void MoveRight(){
    //Your move right code here
}

Technical explanation: Similar to the jump mechanic, we use the Update() function to check if the ‘A’ or ‘D’ keys are pressed, and if they are – we call the appropriate function. The GetKey function will return true as long as the key is being pressed down, which allows your object to continue moving as long as the key is pressed down.

Delving Deeper Into Game Mechanics with C#

Now that we’ve covered some basic game mechanics, let’s delve deeper and explore more complex tasks in C#. The following examples will demonstrate how to program player health, enemy AI, item pickups, and more.

Player Health:

Creating a simple health system for your player is a crucial aspect of most games. The following example lays down a straightforward health system in C#:

public class Player : MonoBehaviour {
    public int health = 100;

    public void TakeDamage(int damage) {
        health -= damage;

        if (health <= 0) {
            Die();
        }
    }

    void Die(){
        //Your player death code here
    }
}

Technical explanation: We declared a public integer variable for health and initialized it at 100. The TakeDamage function takes an integer parameter which corresponds to a potential damage that is subtracted from the player’s current health. We’ve also written a simple death function that can be filled out to suit the needs of any game.

Enemy AI:

A simple enemy AI in a 2D game could be programmed to follow around the player. The following sample code demonstrates this:

public class Enemy : MonoBehaviour {
    public float speed;
    private Transform playerPos;

    void Start(){
        playerPos = GameObject.FindGameObjectWithTag("Player").transform;
    }
    
    void Update() {
        transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);
    }
}

Technical explanation: We start by finding the player’s position. In the Update function, we then continually move the enemy towards the player’s location at a defined speed.

Item Pickups:

Creating consumable items is another integral part of many games, be it power-ups, healing items, or collectibles. Let’s take a simple health pickup:

void OnTriggerEnter2D(Collider2D other){
    if(other.CompareTag("Player")){
        other.GetComponent().health += 50;
        Destroy(gameObject);
    }
}

Technical explanation: The OnTriggerEnter2D function is used to detect when another object is touching the pickup. If that object is tagged as the “Player”, we add 50 to its health attribute and then destroy the health pickup from the game.

Game Scoring:

Lastly, let’s implement a simple game scoring system:

public class Player : MonoBehaviour{
    public static int playerScore = 0;

    void Update(){
        if(transform.position.y < -10){
            Die();
        }
    }

    void Die(){
        //Your player death logic here
        Debug.Log("Game Over! Your score: " + playerScore);
    }
}

Technical explanation: This is a very simple implementation where playerScore is a tracking variable. When the player’s ‘y’ position is less than -10, they “die” and their final score is output to the console.

By mastering these principles and understanding the logic behind them, you should have a great foundation for further exploring the powerful potential of C# in game development.

Further Exploring Game Development with C#

As we journey deeper into the expansive world of game development with C# in Unity, you’ll discover more complex mechanics and features. Here, we’ll delve into a few examples that illustrate the possibilities opened up by mastering this language.

Player Shoot:

A crucial mechanic in many games is the ability for the player to shoot or attack. Let’s implement such a feature:

public class Player : MonoBehaviour {
    public GameObject bulletPrefab;

    void Update(){
        if(Input.GetKeyDown(KeyCode.Space)){
            Shoot();
        }
    }

    void Shoot(){
        Instantiate(bulletPrefab, transform.position, Quaternion.identity);
    }
}

Technical explanation: In this simple implementation, we’re creating a new instance of our bullet object at the player’s location whenever the space bar is pressed.

Object Rotation:

Rotation is a pivotal technique in game development, adding realism and a dynamic environment to your projects. Rotating objects in C# is quite straightforward:

void Update() {
    transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}

Technical explanation: Here we use the Rotate function, which takes a Vector3 argument to define rotations around the x, y, and z axes.

Advanced AI:

Making your game’s enemy AI smarter and more dynamic can dramatically improve your game. Try creating an AI that switches between attack and retreat based on the player’s health:

void Update(){
    if (player.health > 70){
        AttackPlayer();
    } else{
        Retreat();
    }
}

void AttackPlayer(){
    //Attack code here
}

void Retreat(){
    //Retreat code here
}

Technical explanation: In this code, the enemy character will attack if the player’s health is over 70 but will retreat otherwise. It provides a simple example of more dynamic AI behavior.

Player Save and Load:

Creating a save/load system is essential in most games. Here’s a simple example using PlayerPrefs, Unity’s way of saving data:

public class Player : MonoBehaviour{
    public int playerScore = 0;

    void SavePlayer(){
        PlayerPrefs.SetInt("Score", playerScore);
    }

    void LoadPlayer(){
        playerScore = PlayerPrefs.GetInt("Score");
    }
}

Technical explanation: PlayerPrefs allows you to save and load different data types. In this example, we save our score as an integer and can load it whenever we need to. This allows progress to be kept across game sessions.

By putting these coding concepts into practice, you’ll be well on your way to creating engaging, interactive games. It’s important to keep experimenting, exploring new ideas, and pushing your programming abilities, as there are countless techniques to discover in C# game development.

After grasping these fundamental and vital aspects of game development in C#, you may be wondering, “What’s next?”. To keep on flourishing on this journey, we highly recommend you check out our Unity Game Development Mini-Degree.

This comprehensive suite of courses on our platform delves into game development using Unity, one of the world’s most popular game engines—trusted by both indie developers and AAA studios. You’ll explore exciting topics such as game mechanics, animation, and audio effects. The project-based course format ensures you’ll have a robust portfolio of Unity games and projects upon completion. Suitable for all knowledge levels, you can study at your own pace with our flexible learning options.

If you’re looking for a broad selection of training materials beyond the Mini-Degree, feel free to explore our Unity collection. Remember, with Zenva, you can smoothly transition from being a beginner to a professional. We have over 250 professionally-supported courses ready to boost your career. Keep coding, keep creating, and keep improving!

Conclusion

In conclusion, C# offers a wealth of possibilities for creating engaging and dynamic games. Whether you’re exploring player interactions, object behaviors, or artificial intelligence, C# provides a versatile and substantial coding foundation. The examples and concepts explored in this tutorial are just the tip of the iceberg. Game development is a journey of constant learning and continuous improvement.

We invite you to take your C# game development skills further with Zenva. Check out our Unity Game Development Mini-Degree to continue your coding journey and take the next leap in mastering game development. Happy coding!

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.