IGDPD Ch25 Classes
IGDPD Ch25 Classes
CLASSES
1
Topics
Understanding Classes
– The Anatomy of a Class
Class Inheritance
– Superclasses and Subclasses
– Virtual and Override
2
Understanding Classes
Classes are the key concept in Object-Oriented
Programming
A class is a definition of a type of object
There can be many instances of a single class
– Each person in this classroom could be thought of as an
instance of the Human class
C# classes combine data and functionality
– Classes have variables, which are called fields
– Classes have functions, which are called methods
You're already using classes!
– Each C# script you've written is a class
Classes represent objects in your game
3
Understanding Classes
Example: A character in a standard RPG
– Fields you would want for each character
string name; // The character's name
float health; // The amount of health she
has
float healthMax; // Her maximum amount of
health
List<Item> inventory; // List of Items in her inventory
List<Item> equipped; // A List of Items she has equipped
4
The Anatomy of a Class
Includes
The Class Declaration
Fields
Methods
Properties
5
The Anatomy of a Class
We'll explore each part of a class named Enemy
– The Enemy class is for a simple top-down space shooter game
– An Enemy instance moves down the screen at a speed of 10
Includes
– Include code libraries in your project
– Enables standard Unity libraries and objects
• e.g., GameObject, MonoBehaviour, Transform, Renderer, etc.
1 using UnityEngine; // Required for
Unity
2 using System.Collections; // Included by
Unity's default
3 using System.Collections.Generic; // Required to use a List
• Declares two public fields for all instances of the Enemy class
• Each instance has its own value for speed and fireRate
7
The Anatomy of a Class
Methods
– Functions that are part of the class
– Can also be marked public or private
11 void Update() {
12 Move();
13 }
14
15 public virtual void Move() { // Move down the screen
at speed
16 Vector3 tempPos = pos;
17 tempPos.y -= speed * Time.deltaTime; // Makes it
Time-Based!
18 pos = tempPos;
19 }
9
Class Instances as Components
In Unity, all class instances are treated as GameObject
Components
– The class instance can be accessed using GetComponent<>()
Enemy thisEnemy =
this.gameObject.GetComponent<Enemy>();
10
Class Inheritance
Most classes inherit from another class
5 public class Enemy : MonoBehaviour {…}
11
Class Inheritance
We can create a class that inherits from Enemy!
1 using UnityEngine;
2 using System.Collections;
3
4 public class EnemyZig : Enemy {
5 // EnemyZig inherits ALL its behavior from Enemy
6 }
12
Class Inheritance
EnemyZig.Move() overrides Enemy.Move()
4 public class EnemyZig : Enemy {
5 public override void Move () {
6 Vector3 tempPos = pos;
7 tempPos.x = Mathf.Sin(Time.time * Mathf.PI*2) *
4;
8 pos = tempPos; // Uses the pos property of
the superclass
9 base.Move(); // Calls Move() on the
superclass
10 }
11 }
14