Back to Game Development

Module 2: Unity Game Engine

Master Unity's interface, GameObjects, Components, C# scripting, and build your first 3D game

🎮 What is Unity?

Imagine having a complete game studio in one application - 3D modeling tools, physics engine, animation system, scripting, and more! Unity is the world's most popular game engine, used to create everything from mobile games to AAA titles like Hollow Knight, Cuphead, and Among Us.

Simple Definition

Unity is a game engine - a software framework that handles the complex stuff (rendering, physics, audio) so you can focus on making your game fun. It's like having a professional kitchen with all the tools instead of cooking over a campfire!

Unity handles for you:

• 3D rendering and graphics

• Physics simulation

• Audio playback

• Input from keyboard, mouse, gamepad

• Cross-platform deployment (PC, mobile, console, VR)

Why Unity?

Beginner-Friendly

Visual editor, drag-and-drop, tons of tutorials

Cross-Platform

Build once, deploy to 25+ platforms

Asset Store

Thousands of free and paid assets, scripts, tools

Industry Standard

Used by indies and AAA studios worldwide

📚 Learn More:

🖥️ Unity Interface and Workflow

Unity's interface might look overwhelming at first, but it's actually very logical! Think of it like a film studio - you have your scene (the set), hierarchy (cast list), inspector (actor details), project (props warehouse), and game view (camera monitor).

The Five Main Windows

1. Scene View - Your 3D Workspace

This is where you build your game world! You can move, rotate, and scale objects in 3D space. Think of it as your construction site where you place buildings, characters, and props.

Navigation Controls:

Right-click + drag - Look around

Middle-click + drag - Pan view

Scroll wheel - Zoom in/out

F key - Focus on selected object

Q, W, E, R, T - Transform tools

2. Game View - Player's Perspective

This shows what the player will see through the camera. Press Play button to test your game! It's like looking through the camera lens on a movie set.

3. Hierarchy - Scene Contents List

Lists all GameObjects in your current scene. It's organized like a family tree - objects can have parents and children. Moving a parent moves all its children too!

4. Inspector - Object Properties

Shows all the details and settings for the selected GameObject. This is where you adjust position, add components, change colors, etc. It's like the control panel for each object.

5. Project - Asset Library

Contains all your game assets - scripts, textures, models, sounds, etc. It's like your warehouse where you store everything you might need.

💡 Pro Tip:

You can customize the layout! Go to Window > Layouts to choose different arrangements, or drag windows around to create your own. Save your custom layout so you can switch back to it!

🧩 GameObjects, Components, and Prefabs

Unity uses a component-based architecture. Everything in your game is a GameObject, and GameObjects are made up of Components. It's like LEGO - GameObjects are the bricks, and Components are the special pieces (wheels, windows, etc.) you attach to them.

GameObjects Explained

A GameObject is a container. By itself, it's just a position in 3D space. You add Components to give it functionality - a mesh to make it visible, a collider to make it solid, a script to make it interactive.

Example: A Player Character

GameObject: "Player"

Transform - Position, rotation, scale

Mesh Renderer - Makes it visible

Mesh Filter - Defines the 3D shape

Rigidbody - Adds physics

Capsule Collider - Collision detection

Player Controller Script - Movement logic

Common Components

Transform

Every GameObject has this! Controls position (X, Y, Z), rotation (angles), and scale (size). It's the most fundamental component.

Rigidbody

Adds physics! Objects with Rigidbody fall with gravity, can be pushed, and collide realistically. Essential for any physics-based gameplay.

Collider

Defines the physical shape for collisions. Box, Sphere, Capsule, or Mesh colliders. Without this, objects pass through each other!

Renderer

Makes objects visible! Mesh Renderer for 3D models, Sprite Renderer for 2D images. Controls materials and how the object looks.

Camera

Defines what the player sees. You can have multiple cameras for split-screen, minimaps, or cutscenes. Main Camera is created by default.

Light

Illuminates your scene! Directional (sun), Point (light bulb), Spot (flashlight), or Area lights. Lighting makes or breaks visual quality.

Prefabs - Reusable Templates

A Prefab is a reusable GameObject template. Create an enemy once, save it as a Prefab, then spawn 100 copies! Change the Prefab, and all instances update automatically.

Creating a Prefab:

1. Create and configure your GameObject in the scene

2. Drag it from Hierarchy to Project window

3. Now it's a Prefab! Drag it back to create instances

Perfect for: Enemies, bullets, collectibles, obstacles

💻 C# Scripting for Unity

Unity uses C# (C-Sharp) for scripting. Don't worry if you're new to programming - Unity's C# is beginner-friendly! Scripts are Components that you attach to GameObjects to control their behavior.

Your First Unity Script

// PlayerController.cs - Basic movement script

using UnityEngine;

public class PlayerController : MonoBehaviour

{

// Variables (visible in Inspector)

public float speed = 5f;

public float jumpForce = 10f;

// Private variables

private Rigidbody rb;

private bool isGrounded;

// Called once when script starts

void Start()

{

// Get the Rigidbody component

rb = GetComponent<Rigidbody>();

}

// Called every frame (60 times per second)

void Update()

{

// Get input from arrow keys or WASD

float horizontal = Input.GetAxis("Horizontal");

float vertical = Input.GetAxis("Vertical");

// Create movement vector

Vector3 movement = new Vector3(horizontal, 0, vertical);

// Move the player

transform.Translate(movement * speed * Time.deltaTime);

// Jump when spacebar pressed

if (Input.GetKeyDown(KeyCode.Space) && isGrounded)

{

rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);

isGrounded = false;

}

}

// Called when colliding with another object

void OnCollisionEnter(Collision collision)

{

// Check if we hit the ground

if (collision.gameObject.CompareTag("Ground"))

{

isGrounded = true;

}

}

}

Key Unity Methods

Start()

Called once when the GameObject is created. Use it for initialization - getting components, setting up variables, etc.

Update()

Called every frame. Use for input handling, non-physics movement, timers, and anything that needs to happen continuously.

FixedUpdate()

Called at fixed intervals (50 times/sec by default). Use for physics operations like applying forces. More consistent than Update().

OnCollisionEnter()

Called when this object collides with another. Perfect for detecting hits, collecting items, or triggering events.

💡 Important Concepts:

  • Time.deltaTime: Time since last frame. Multiply by this to make movement frame-rate independent!
  • GetComponent: Access other components on the same GameObject
  • transform: Quick access to the Transform component
  • gameObject: Reference to the GameObject this script is attached to

⚡ Physics and Collision Detection

Unity's physics engine (PhysX) handles realistic movement, gravity, collisions, and forces. You don't need to understand complex physics math - Unity does it for you!

Rigidbody Physics

Add a Rigidbody component to make an object respond to physics. It will fall with gravity, bounce off surfaces, and react to forces.

Mass: How heavy the object is (affects momentum)

Drag: Air resistance (higher = slows down faster)

Angular Drag: Rotation resistance

Use Gravity: Should it fall down?

Is Kinematic: Ignore physics, move manually (for platforms)

Constraints: Lock position or rotation on specific axes

Collision Types

Colliders - Physical Boundaries

Colliders define the physical shape. Objects with colliders can't pass through each other.

Box Collider: Rectangular shape (walls, crates)

Sphere Collider: Round shape (balls, planets)

Capsule Collider: Pill shape (characters)

Mesh Collider: Exact model shape (complex objects)

Triggers - Detection Zones

Check "Is Trigger" on a collider to make it a detection zone. Objects pass through but trigger events. Perfect for collectibles, checkpoints, or danger zones!

void OnTriggerEnter(Collider other)

{

if (other.CompareTag("Player"))

{

Debug.Log("Player entered trigger!");

}

}

⚠️ Common Mistakes:

  • • Forgetting to add a Collider - objects will pass through each other!
  • • Using Mesh Collider for moving objects - very slow! Use primitive colliders instead
  • • Moving Rigidbody in Update() - use FixedUpdate() or AddForce() instead
  • • Not checking for null - always verify GetComponent() returned something!

🎬 Animation System Basics

Unity's Animator system lets you create smooth transitions between animations - walking, running, jumping, attacking. It uses a state machine to control which animation plays when.

Animation Workflow

Step 1: Import Animations

Get animations from the Asset Store, create them in Blender, or use Unity's Animation window to record keyframes.

Step 2: Create Animator Controller

Right-click in Project → Create → Animator Controller. This is your animation state machine.

Step 3: Add States

Drag animations into the Animator window. Each becomes a state (Idle, Walk, Run, Jump).

Step 4: Create Transitions

Right-click a state → Make Transition → Click target state. Set conditions for when to transition (e.g., speed > 0.1 = start walking).

Controlling Animations from Code

// AnimationController.cs

private Animator animator;

void Start()

{

animator = GetComponent<Animator>();

}

void Update()

{

// Set parameters to control transitions

float speed = Input.GetAxis("Vertical");

animator.SetFloat("Speed", speed);

// Trigger one-shot animations

if (Input.GetKeyDown(KeyCode.Space))

{

animator.SetTrigger("Jump");

}

// Set boolean states

animator.SetBool("IsGrounded", isGrounded);

}

🎯 Animation Tips:

  • • Use Blend Trees for smooth transitions (walk to run based on speed)
  • • Keep transition times short (0.1-0.25s) for responsive feel
  • • Use Root Motion for cutscenes, disable for gameplay
  • • Layer animations (upper body attack while lower body walks)

🎯 Complete Example: Simple 3D Platformer

Let's build a complete 3D platformer game in Unity! This project demonstrates GameObjects, Components, C# scripting, physics, and basic game mechanics.

Step 1: Scene Setup

Create the Ground:

1. GameObject → 3D Object → Plane (this is your ground)

2. Scale it up: Transform scale (10, 1, 10)

3. Add a material: Create → Material, change color, drag to plane

Create the Player:

1. GameObject → 3D Object → Capsule

2. Position at (0, 1, 0) so it's above ground

3. Add Component → Rigidbody

4. Rigidbody: Set Constraints → Freeze Rotation X, Y, Z (prevents tipping over)

5. Tag it as "Player" (top of Inspector)

Create Platforms:

1. GameObject → 3D Object → Cube

2. Scale to (3, 0.5, 3) for a platform

3. Position at different heights

4. Duplicate (Ctrl+D) to create more platforms

Create Collectibles:

1. GameObject → 3D Object → Sphere

2. Scale to (0.5, 0.5, 0.5)

3. Add Component → Box Collider, check "Is Trigger"

4. Tag as "Collectible"

5. Duplicate and place around the level

Step 2: Player Controller Script

// PlayerController.cs - Complete movement and collection

using UnityEngine;

using UnityEngine.UI;

public class PlayerController : MonoBehaviour

{

// Movement settings

public float moveSpeed = 5f;

public float jumpForce = 8f;

public float rotationSpeed = 10f;

// Components

private Rigidbody rb;

private bool isGrounded;

// Game state

private int score = 0;

public Text scoreText; // Drag UI Text here in Inspector

void Start()

{

rb = GetComponent<Rigidbody>();

UpdateScoreText();

}

void Update()

{

// Get input

float horizontal = Input.GetAxis("Horizontal");

float vertical = Input.GetAxis("Vertical");

// Create movement direction

Vector3 movement = new Vector3(horizontal, 0, vertical).normalized;

// Move player

if (movement.magnitude >= 0.1f)

{

// Move

Vector3 moveDir = movement * moveSpeed * Time.deltaTime;

transform.Translate(moveDir, Space.World);

// Rotate to face movement direction

Quaternion toRotation = Quaternion.LookRotation(movement, Vector3.up);

transform.rotation = Quaternion.Lerp(

transform.rotation,

toRotation,

rotationSpeed * Time.deltaTime

);

}

// Jump

if (Input.GetKeyDown(KeyCode.Space) && isGrounded)

{

rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);

isGrounded = false;

}

}

// Detect ground collision

void OnCollisionEnter(Collision collision)

{

if (collision.gameObject.CompareTag("Ground") ||

collision.gameObject.CompareTag("Platform"))

{

isGrounded = true;

}

}

// Collect items

void OnTriggerEnter(Collider other)

{

if (other.CompareTag("Collectible"))

{

// Destroy the collectible

Destroy(other.gameObject);

// Increase score

score += 10;

UpdateScoreText();

// Play sound (if you have an AudioSource)

// GetComponent<AudioSource>().Play();

}

}

void UpdateScoreText()

{

if (scoreText != null)

{

scoreText.text = "Score: " + score;

}

}

}

Step 3: Rotating Collectible Script

// RotateObject.cs - Makes collectibles spin

using UnityEngine;

public class RotateObject : MonoBehaviour

{

public float rotationSpeed = 100f;

void Update()

{

// Rotate around Y axis

transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);

}

}

Step 4: Camera Follow Script

// CameraFollow.cs - Smooth camera that follows player

using UnityEngine;

public class CameraFollow : MonoBehaviour

{

public Transform target; // Drag player here

public Vector3 offset = new Vector3(0, 5, -7);

public float smoothSpeed = 0.125f;

void LateUpdate() // After player moves

{

if (target == null) return;

// Calculate desired position

Vector3 desiredPosition = target.position + offset;

// Smoothly move camera

Vector3 smoothedPosition = Vector3.Lerp(

transform.position,

desiredPosition,

smoothSpeed

);

transform.position = smoothedPosition;

// Look at player

transform.LookAt(target);

}

}

Step 5: Add UI

1. Right-click Hierarchy → UI → Canvas (creates Canvas and EventSystem)

2. Right-click Canvas → UI → Text - TextMeshPro (or legacy Text)

3. Position text in top-left corner

4. Set text to "Score: 0"

5. Drag this Text object to the Player's "Score Text" field in Inspector

🎓 What You've Built:

  • • Complete 3D platformer with physics-based movement
  • • Player controller with jumping and rotation
  • • Collectible system with score tracking
  • • Smooth camera follow system
  • • UI integration for game feedback
  • • Proper use of GameObjects, Components, and Scripts

📚 Learning Resources

Official Unity Resources

Community Resources

🎯 What's Next?

You now know Unity fundamentals! In the next module, we'll dive into 3D Graphics and Rendering - learning about 3D modeling with Blender, materials, shaders, lighting, and creating beautiful game visuals!