Welcome to your first real coding lesson!
Let’s start with one of the most important concepts in C#:
Variables – the way we store stuff in memory so we can use it in our games.
Imagine a game with no memory. The player collects coins… then forgets.
They take damage… then feel fine.
Sounds like a forgetful fish simulator 🐟
🧠 What is a Variable?
A variable is like a labeled box that holds information.
int score = 10;
This says:
“I want a box called
score
that holds a number, and I’m putting 10 in it.”
In C#, we have to tell the computer what type of data we want to store.
📦 Common Data Types in Unity
Type | Description | Example |
---|---|---|
int | Whole numbers | int coins = 5; |
float | Decimal numbers | float speed = 3.5f; |
bool | True or false | bool isJumping = false; |
string | Text (inside quotes) | string name = "Alex"; |
char | A single character | char key = 'A'; |
🧙♂️ Note:
float
needs anf
at the end, like3.5f
– Unity insists.
🎮 Example in Unity
Let’s create a script called PlayerStats.cs
and use variables to represent a player’s data:
UnityEngine;
public class PlayerStats : MonoBehaviour
{
public int health = 100;
public float moveSpeed = 5.5f;
public string playerName = "Player1";
public bool hasPowerUp = false;
}
Attach this script to any GameObject, and these variables will appear in the Inspector for easy editing.
Unity even lets you tweak them mid-game for testing! 🔥
🤔 What’s “public” and “private”?
public
= visible in the Inspector and accessible by other scriptsprivate
= hidden from the Inspector (default if you don’t write anything)
We’ll dive deeper into access modifiers later. For now, just know:
If you want to see it in the Unity editor — make it public
.
✨ Mini Challenge: Create Your Own Stats Script
- Create a new script called
EnemyStats.cs
- Add the following variables:
int health
float damage
string enemyName
bool isBoss
- Attach it to a new GameObject in the scene
- Change values in the Inspector and hit Play
🎉 You’ve just made a system that can handle unique enemies in your game!
🧠 Recap
- Variables store game info like score, health, speed, etc.
- You must choose the right data type for each value
- Use
public
to show variables in Unity’s Inspector - Now you’re not just a player—you’re a game architect
🚀 What’s Next?
Next up, you’ll learn how to actually do stuff with your variables using methods and parameters.
🛠️ Go to Lesson 8 → Methods and Parameters in Unity C#