Variables and Conditional Statements Basics

Learn the basics of variables and conditional statements in C# programming. Covers variable types, access modifiers, Unity lifecycle methods, and conditional statements.

What is a Variable?

Think of a variable as a box that stores data. It's used to store things like player health, score, name, etc. in games.

Variable Types

Integer (int)

  • Description: Can only store whole numbers (no decimal points)
  • Example: int hp = 100; (health 100)
  • Use cases: Health, score, level, count, etc.

Float

  • Description: Stores numbers with decimal points
  • Example: float pi = 3.14f; (must add 'f')
  • Use cases: Speed, distance, ratio, etc.

String

  • Description: Stores text
  • Example: string myName = "John"; (quotes required)
  • Use cases: Name, message, description, etc.

Boolean (bool)

  • Description: Stores only true or false
  • Example: bool isGameOver = false;
  • Use cases: Game over status, button activation, etc.

Access Modifiers

private

  • Description: Can only be used within this script
  • Example: private int hp = 100;
  • When to use: When other scripts don't need to access it

public

  • Description: Visible and editable in Unity Inspector window
  • Example: public int hp = 100;
  • When to use: When you want to change values in Inspector during gameplay

Unity Lifecycle Methods

Start()

  • When executed: Runs only once when the game starts
  • Purpose: Initial setup, variable initialization
  • Example: Set health to 100, display start message

Update()

  • When executed: Runs continuously every frame (about 60 times per second)
  • Purpose: Things that need continuous checking
  • Example: Key input detection, collision checking

Conditional Statements (if)

Conditional statements express "if ~ then".

if (hp <= 0)
{
    Debug.Log("Game Over!");
}
  • Behavior: If hp is 0 or less, output "Game Over!" message
  • Usage: Game over when health reaches 0, level up when score exceeds 100, etc.

Arithmetic Operations

Operations to add or subtract numbers from variables.

hp = hp - 100;  // Subtract 100 from hp
hp = hp + 50;   // Add 50 to hp
hp = hp * 2;    // Multiply hp by 2
hp = hp / 2;    // Divide hp by 2

Debug.Log

A tool to check if code is running correctly.

Debug.Log("Hello!");
Debug.Log("Current health: " + hp);
  • You can check messages in the Console window at the bottom of Unity
  • Useful for checking variable values or finding errors

← Back to Table of Contents