Overview
C# (pronounced "C-sharp") is the programming language used to write game logic in Unity. Understanding C# fundamentals is essential for mastering Unity. However, learning everything about C# at once can be overwhelming for beginners.
This article focuses on the absolute basics of C# you need to know to start writing scripts in Unity: variables, data types, functions, and basic control flow statements like if and for loops. The goal is to get you comfortable writing simple logic in Unity.
Variables and Data Types
A variable is like a "box" that holds data such as numbers or text. In C#, you must explicitly specify the data type to indicate what kind of data the box will hold.
Let's look at the basic data types commonly used in Unity:
| Data Type | Description | Example |
|---|---|---|
int | Integer numbers (-2, -1, 0, 1, 2...) | int playerScore = 100; |
float | Floating-point numbers (decimals). Append f to the number. | float speed = 5.5f; |
bool | Boolean values (either true or false) | bool isGameOver = false; |
string | Text strings. Enclosed in double quotes. | string playerName = "Hero"; |
Vector3 | 3D vector (x, y, z coordinates). Represents positions and directions. | Vector3 startPosition = new Vector3(0, 1, 0); |
GameObject | Unity's game object itself. | public GameObject playerObject; |
Declaring and Using Variables
Variables are declared with [DataType] [variableName]; and assigned values using =.
using UnityEngine;
public class VariableExample : MonoBehaviour
{
// Variable declarations
int health; // Health (integer)
float moveSpeed; // Movement speed (decimal)
bool isJumping; // Is jumping? (boolean)
void Start()
{
// Assign values to variables
health = 100;
moveSpeed = 7.5f;
isJumping = false;
// Output variable values to console
Debug.Log("Health: " + health);
Debug.Log("Move Speed: " + moveSpeed);
}
}
Public Variables
Adding the public keyword before a variable makes it visible in Unity's Inspector window, allowing non-programmers to adjust values. This is extremely useful for game balance tweaking.
using UnityEngine;
public class PlayerSettings : MonoBehaviour
{
// Public variables appear in Inspector
public string playerName = "Default Name";
public float jumpPower = 10f;
public int maxHealth = 200;
}
Functions (Methods)
Functions (or methods) are packaged sets of operations. By defining functions, you can call and reuse the same operations multiple times.
C# functions are defined as follows:
[ReturnType] [FunctionName]([Parameters]) { ...code... }
- Return type: The data type of the value returned after the function completes. Use
voidif no value is returned. - Function name: The name of the function. Use descriptive names that indicate what it does.
- Parameters: Information passed to the function. Separate multiple parameters with commas. Leave empty if none needed.
using UnityEngine;
public class FunctionExample : MonoBehaviour
{
void Start()
{
// Call a function
SayHello();
// Call a function with arguments and receive return value
int result = Add(10, 5);
Debug.Log("10 + 5 = " + result);
}
// Function with no parameters or return value
void SayHello()
{
Debug.Log("Hello!");
}
// Function that takes two int parameters and returns an int
int Add(int a, int b)
{
int sum = a + b;
return sum; // Return value using the return keyword
}
}
Unity's Start and Update are special types of functions that are called by the Unity engine at specific times.
Control Flow Statements
Control flow statements control the flow of your program. Here we'll introduce the most basic ones: if and for.
if Statements (Conditional Branching)
if statements create branches in your code based on conditions: "if X is true, do Y."
int score = 85;
if (score >= 80)
{
Debug.Log("Excellent!");
}
else if (score >= 60)
{
Debug.Log("You passed.");
}
else
{
Debug.Log("Try harder next time.");
}
for Loops (Iteration)
for loops repeat the same operations a specified number of times.
// Repeat 10 times, from 0 to 9
for (int i = 0; i < 10; i++)
{
Debug.Log("Current count: " + i);
}
For example, this can be used to spawn multiple enemy characters at once.
Summary
In this article, we covered the C# basics you need to start writing scripts in Unity.
- Variables: Boxes that hold data.
int,float,bool,stringare the basics. - Functions: Grouped operations.
voidmeans no return value. ifstatements: Branch code based on conditions.forloops: Repeat operations.
These elements form the foundation of all scripts. It might feel difficult at first, but these concepts will become natural as you practice writing simple scripts in Unity. Start by using these basics as tools to add simple behaviors and rules to your games.