C# for Unity Game Development
Introduction to C#
Your First Lines of C#
C# (pronounced “C sharp”) is a programming language created by Microsoft. Think of it as a set of instructions you can give a computer to make it do things, from running a game to powering a website. For our purposes, it’s the primary language used to build games in the Unity engine.
At its heart, C# is an object-oriented language. This sounds complex, but the idea is simple: we organize our code into self-contained modules, or “objects,” that represent things in our program. An object could be a player, an enemy, or a button on the screen. Each object has its own data (like health points) and behaviors (like the ability to jump). This approach helps keep code organized and reusable.
Let’s start with the classic first program: making the computer say “Hello, World!”. This example shows the basic structure of a C# application.
using System;
class Program
{
static void Main()
{
// This line prints the text to the console.
Console.WriteLine("Hello, World!");
}
}
Every C# program has a few key parts:
using System;tells our program to include a pre-written library of code calledSystem, which contains fundamental tools like theConsole.WriteLine()function.class Programis a container for our code. Everything in C# lives inside a class.static void Main()is the entry point. When the program runs, it looks for theMainmethod and starts executing the code inside its curly braces{}.Console.WriteLine(...)is the instruction that actually does something: it prints a line of text to the console.- Notice the semicolons
;at the end of the lines. In C#, semicolons act like periods in a sentence, marking the end of a command.
Variables and Data
Programs need to store and manage information. We do this using variables. A variable is just a named container in the computer’s memory that holds a piece of data. Each variable must have a specific data type, which tells the computer what kind of information it will store.
Think of data types like different kinds of boxes. You'd use a small box for a ring, a bigger box for a book, and a specially shaped box for a hat. You wouldn't put soup in a shoebox. In programming, you use an
intfor a whole number and astringfor text.
Here are the most common data types you'll encounter:
| Data Type | Purpose | Example |
|---|---|---|
int | Whole numbers | int score = 100; |
float | Numbers with decimals | float health = 75.5f; |
double | High-precision decimals | double pi = 3.14159265; |
string | Text | string name = "Player1"; |
bool | True or false values | bool isAlive = true; |
When you create a variable, you declare its type and name, and you can initialize it with a starting value.
// Declaring and initializing variables
int playerScore = 0;
string playerName = "Alex";
bool hasKey = false;
// You can change a variable's value later
playerScore = 150;
hasKey = true;
Console.WriteLine(playerName + " has " + playerScore + " points.");
Controlling the Flow
A program doesn't just run from top to bottom. We need ways to make decisions and repeat actions. This is called control flow.
The most common way to make a decision is with an if statement. It checks if a condition is true and runs a block of code only if it is. You can add an else block to run code if the condition is false.
int health = 50;
if (health > 75)
{
Console.WriteLine("You are in good shape.");
}
else if (health > 25)
{
Console.WriteLine("You should find a health pack.");
}
else
{
Console.WriteLine("Warning: Critical health!");
}
To repeat actions, we use loops. A for loop is great when you know exactly how many times you want to repeat something. It has three parts: an initializer, a condition, and an iterator.
// This loop runs 5 times
for (int i = 0; i < 5; i++)
{
// i starts at 0 and goes up to 4
Console.WriteLine("Loading... " + i);
}
A while loop is used when you want to keep repeating an action as long as a certain condition remains true. You don't know ahead of time how many repetitions there will be.
int enemiesRemaining = 3;
while (enemiesRemaining > 0)
{
Console.WriteLine("An enemy was defeated.");
enemiesRemaining = enemiesRemaining - 1; // Decrement the count
}
Console.WriteLine("All enemies defeated!");
Organizing Code with Methods
As programs grow, you don't want to cram all your code into the Main method. Instead, you can group related lines of code into reusable blocks called methods (or functions). A method is a named block of code that performs a specific task.
Methods can take in data as parameters and can return a value once they are finished.
class Program
{
static void Main()
{
// Call the method and store its result
int sum = AddNumbers(5, 10);
Console.WriteLine("The sum is: " + sum);
// Call a method that doesn't return anything
SayGoodbye();
}
// This method takes two integers and returns their sum
static int AddNumbers(int num1, int num2)
{
return num1 + num2;
}
// This method doesn't return a value (void)
static void SayGoodbye()
{
Console.WriteLine("Goodbye!");
}
}
Using methods makes your code cleaner, easier to read, and allows you to reuse code without copying and pasting.
Now that you've seen the basics, it's time to check your understanding.
What is the primary purpose of the static void Main() method in a C# program?
Which data type is most appropriate for storing a player's name, such as "Gandalf"?
These are the fundamental building blocks of C#. With variables, control structures, and methods, you can start to build the logic for nearly any program or game.