VARIABLES & THE INSPECTOR

Your complete step-by-step walkthrough — follow at your own pace, tick every box

Course: Game On (9GAMZA) Lesson: T1 — L07 Time: ~75 min Unity: 2022.3.x Outcomes: G5-1, G5-2, G5-4
TOTAL XP 0 / 50 XP
1
What Are Variables?
~10 min • Understand data types and why variables matter.
+10 XP

Key Terms

Variable
A named container that stores a value. Like a labelled box — the label is the name, the contents are the value.
Data Type
What KIND of data the variable holds — number, text, true/false, etc.
int
A whole number (integer). Examples: 0, 5, -3, 100. No decimals.
float
A decimal number. Examples: 3.14f, 0.5f, -2.7f. Always ends with "f".
string
Text wrapped in double quotes. Examples: "Hello", "Player1", "Game Over".
bool
True or false — only two possible values. Used for on/off, yes/no decisions.
💡
Analogy: Variables are like backpacks. Each backpack has a label (the variable name) and carries a specific type of item. An "int backpack" only carries whole numbers. A "string backpack" only carries text. You can swap what's inside anytime, but the type of item must match the backpack!
1.1
Open your Unity project from last lesson. Your player should already move with A/D keys.
1.2
Open your PlayerMovement script (double-click it in the Project window). Find this line inside Update():
float speed = 5.0f;
This is already a variable! It's called speed, has the type float, and holds the value 5.0.
1.3
Read through the four data types below. Every variable in C# must have ONE of these types:
int
Integer
Whole numbers only. No decimals.
int lives = 3;
int score = 0;
int level = 1;
float
Floating Point
Decimal numbers. Needs "f" at the end.
float speed = 5.0f;
float gravity = -9.8f;
float jumpForce = 7.5f;
string
String
Text in double quotes. Any characters.
string playerName = "Hero";
string weapon = "Sword";
string message = "Game Over";
bool
Boolean
Only true or false. Yes/no decisions.
bool isAlive = true;
bool hasKey = false;
bool isGrounded = true;
1.4
Quick quiz: What data type would you use for each of these? (Think first, then check the answers below.)
  • The player's health points (e.g., 100) → int
  • Movement speed (e.g., 4.5) → float
  • The player's name (e.g., "Ninja") → string
  • Whether the game is paused (yes/no) → bool
  • Number of coins collected (e.g., 7) → int
  • Jump height (e.g., 12.3) → float
Checkpoint: "I can name the 4 data types (int, float, string, bool) and give examples of each."
2
Public vs Private Variables
~10 min • Learn the difference and why it matters.
+10 XP

Key Terms

public
Everyone can see and change this variable — including the Unity Inspector. Use for settings you want to tune.
private
Only THIS script can see and change this variable. Hidden from the Inspector. Use for internal data.
Inspector
The Unity panel that shows a GameObject's components and their settings. Public variables appear here!
Declaration
Creating a variable for the first time: giving it a type, a name, and an initial value.
💡
Analogy: Public = a whiteboard in the classroom — everyone can see and write on it. Private = your diary — only you can read and write in it. Game designers make speed, jump force, etc. public so they can tweak them in Unity without opening the code!
2.1
In your PlayerMovement script, find this line inside Update():
float speed = 5.0f;
Currently this variable is inside the function. It gets recreated every frame. We need to move it to the top of the class and make it public.
2.2
DELETE the line float speed = 5.0f; from inside Update().
2.3
ADD a new line ABOVE the Start() function, right after the opening { of the class. Type:
public float speed = 5.0f;
Your script should now look like this:
using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 5.0f; void Start() { } void Update() { float moveInput = Input.GetAxis("Horizontal"); transform.Translate(moveInput * speed * Time.deltaTime, 0, 0); } }
What changed? We moved speed outside of Update and added the keyword public. Now speed is a class-level variable (also called a field) — it exists for the entire life of the script, not just one frame.
2.4
Save the script (Ctrl+S). Go back to Unity. Click on your Player object in the Hierarchy.
2.5
Look at the Inspector! Under "Player Movement (Script)" you should now see a Speed slider! It shows the value 5.
This is the magic! Because we made speed public, Unity automatically shows it in the Inspector. You can now change speed without editing code.
2.6
Press Play. While the game is running, drag the Speed slider to 15. Watch your player speed up! Try 1 — super slow! Try 50 — zoom!
WARNING: Changes made in Play mode are TEMPORARY. When you press Stop, the value goes back to what it was before. This is by design — it lets you experiment without fear!
2.7
Press Stop. Now change Speed in the Inspector to your preferred value (try 8). This change will stick because you made it outside Play mode.
Pro tip: The Inspector value overrides the code value. Even though your code says = 5.0f, if you set it to 8 in the Inspector, it stays at 8. The code value is just the default.
What you should see
Inspector showing "Speed" slider under PlayerMovement script. You can drag to change the value.
Checkpoint: "My Speed variable appears in the Inspector and I can change it without editing code."
Troubleshooting:
  • Speed not showing in Inspector? Did you write public before float? Did you save the script?
  • Error in Console? Make sure you deleted the old float speed = 5.0f; from inside Update(). You should NOT have it in both places.
  • Speed resets after Play? That's normal! Changes in Play mode are always temporary.
3
Add More Variables — Lab
~20 min • Create jump force, lives, and player name variables.
+10 XP
💡
Game developers use variables for everything: speed, health, lives, score, jump height, gravity, damage... Making them public means designers can tune the game without touching code.
3.1
Open your PlayerMovement script. Below your public float speed line, add these new variables:
public float speed = 5.0f; public float jumpForce = 10.0f; public int lives = 3; public string playerName = "Hero"; public bool isAlive = true;
3.2
Now add a Debug.Log inside Start() to test your variables:
void Start() { Debug.Log("Player: " + playerName); Debug.Log("Lives: " + lives); Debug.Log("Speed: " + speed); Debug.Log("Jump Force: " + jumpForce); Debug.Log("Is Alive: " + isAlive); }
What is the + doing? The + sign joins text together (this is called concatenation). So "Player: " + playerName becomes "Player: Hero" in the Console.
3.3
Save (Ctrl+S). Go to Unity. Click on your Player. Check the Inspector — you should see all 5 variables listed!
3.4
Change some values in the Inspector:
  • Set Player Name to your real name
  • Set Lives to 5
  • Set Speed to 8
  • Toggle Is Alive on/off (checkbox)
3.5
Press Play. Open the Console (Window → General → Console). You should see YOUR values printed — the ones you set in the Inspector, not the code defaults!
3.6
Stop Play mode. Your full script should look like this:
using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 5.0f; public float jumpForce = 10.0f; public int lives = 3; public string playerName = "Hero"; public bool isAlive = true; void Start() { Debug.Log("Player: " + playerName); Debug.Log("Lives: " + lives); Debug.Log("Speed: " + speed); Debug.Log("Jump Force: " + jumpForce); Debug.Log("Is Alive: " + isAlive); } void Update() { float moveInput = Input.GetAxis("Horizontal"); transform.Translate(moveInput * speed * Time.deltaTime, 0, 0); } }
3.7
Experiment: Try adding your OWN variable. Choose a type, pick a name, give it a value. Some ideas:
  • public int score = 0; — track the player's score
  • public float gravity = -9.8f; — gravity strength
  • public bool hasShield = false; — does player have a shield?
  • public string weaponName = "Sword"; — current weapon
Checkpoint: "I have 5+ public variables in my script. They all appear in the Inspector and print to the Console."
Troubleshooting:
  • "Can't add script component" error? The class name in code MUST match the file name. File = PlayerMovement.cs, class = PlayerMovement.
  • Variable not appearing in Inspector? Make sure it has public before the type. Also check: did you put it ABOVE Start(), not inside a function?
  • Strings need double quotes! Write "Hello", not 'Hello' or just Hello.
  • Floats need an f! Write 5.0f, not 5.0. The f tells C# this is a float, not a double.
4
Variables in Action — Game Tuning
~20 min • Use variables to control game behaviour and tune your game.
+10 XP
💡
Why is this important? Professional game developers spend HOURS tuning variables. How fast should the player run? How high should they jump? How much damage does a fireball do? These are ALL variables that get adjusted through playtesting — and public variables in the Inspector make this fast and easy.
4.1
Add vertical movement. In your Update() function, add these lines BELOW the existing movement code:
void Update() { float moveInput = Input.GetAxis("Horizontal"); transform.Translate(moveInput * speed * Time.deltaTime, 0, 0); // Vertical movement (W/S or Up/Down arrows) float verticalInput = Input.GetAxis("Vertical"); transform.Translate(0, verticalInput * speed * Time.deltaTime, 0); }
What changed? We added a second GetAxis for "Vertical" (W/S keys). The Translate now moves on the Y axis (up/down) instead of X (left/right).
4.2
Save and Play. Test with WASD — you can now move in all 4 directions!
4.3
Create a separate vertical speed. What if you want the player to move faster horizontally than vertically? Add a new variable at the top:
public float speed = 5.0f; public float verticalSpeed = 3.0f;
Then change your vertical Translate to use verticalSpeed instead of speed:
transform.Translate(0, verticalInput * verticalSpeed * Time.deltaTime, 0);
4.4
Save and Play. Now you have TWO speed sliders in the Inspector! Adjust them independently to get the feel you want.
4.5
Add player boundaries. The player can fly off screen! Let's use variables to set limits. Add two new variables at the top:
public float xBound = 8.0f; public float yBound = 4.0f;
Then add this boundary check at the END of Update():
// Keep player within boundaries if (transform.position.x > xBound) transform.position = new Vector3(xBound, transform.position.y, 0); if (transform.position.x < -xBound) transform.position = new Vector3(-xBound, transform.position.y, 0); if (transform.position.y > yBound) transform.position = new Vector3(transform.position.x, yBound, 0); if (transform.position.y < -yBound) transform.position = new Vector3(transform.position.x, -yBound, 0);
What this does: If the player's X position goes past xBound (or -xBound), we snap them back to the boundary. Same for Y. The values are public so you can tune the play area size in the Inspector!
4.6
Save and Play. Your player can no longer leave the screen! Adjust xBound and yBound in the Inspector to match your camera view.
4.7
Game Tuning Challenge: Spend 5 minutes playtesting. Adjust your variables to get the "feel" right:
  • What speed feels responsive but controllable?
  • What boundaries keep the player visible?
  • Does vertical speed need to match horizontal speed?
Write down your final values in a comment at the top of your script:
// Tuned values: speed=8, verticalSpeed=5, xBound=7.5, yBound=4
4.8
Save your scene (Ctrl+S in Unity) and your script (Ctrl+S in code editor).
What you should see
Player moves with WASD, stays within boundaries. Inspector shows Speed, VerticalSpeed, xBound, yBound variables.
Checkpoint: "My player moves in 4 directions, stays within boundaries, and I tuned all variables in the Inspector."
Troubleshooting:
  • Player teleports? Check the if-statements — make sure you typed > and < correctly. Don't mix them up!
  • Boundaries don't work? Make sure xBound/yBound are public and set to reasonable values (try 8 and 5).
  • Player still moves through boundary? The boundary code must be BELOW the movement code in Update(). Order matters!
5
Extension Challenges
If time permits • Take your variables further.
+10 XP

Only if you've finished Sections 1-4.

5.1
Challenge 1: Sprint Mechanic. Add a public float sprintMultiplier = 2.0f; variable. When the player holds Left Shift, multiply speed by the sprint multiplier:
float currentSpeed = speed; if (Input.GetKey(KeyCode.LeftShift)) currentSpeed = speed * sprintMultiplier;
Then use currentSpeed instead of speed in your Translate.
5.2
Challenge 2: Display Variables on Screen. Add a Debug.Log inside Update() that shows the player's position:
Debug.Log("Position: " + transform.position);
Watch the Console as you move — you'll see X and Y values changing in real time!
5.3
Challenge 3: Private Variables. Add some private variables and notice they DON'T appear in the Inspector:
private int deathCount = 0; private float timePlayed = 0f;
In Update, add: timePlayed += Time.deltaTime; — this counts seconds played.
5.4
Challenge 4: SerializeField. What if you want a variable to appear in the Inspector but stay private? Use [SerializeField]:
[SerializeField] private float secretSpeed = 3.0f;
This is the professional way — it keeps encapsulation while allowing Inspector editing.
5.5
Challenge 5: Create a Second Script. Create a new C# script called "GameManager". Give it public variables for: int totalScore, int highScore, bool isGameOver, string levelName. Attach it to an empty GameObject called "GameManager". No code in Start/Update needed — just declare the variables.
🎮
Research: Look up "Unity Inspector Attributes" — what do [Range(0,10)], [Header("Movement")], and [Tooltip("...")] do? Try adding them to your variables!