Game Development Reference
In-Depth Information
Listing 6-1. Weapon.cs: Abstract Base Class for Player Weapons
01 //------------------------------------------------
02 using UnityEngine;
03 using System.Collections;
04 //------------------------------------------------
05 public class Weapon : MonoBehaviour
06 {
07 //Custom enum for weapon types
08
public enum WEAPON_TYPE {Punch=0, Gun=1};
09
10 //Weapon type
11 public WEAPON_TYPE Type = WEAPON_TYPE.Punch;
12
13 //Damage this weapon causes
14 public float
Damage
= 0.0f;
15
16 //Range of weapon (linear distance outwards from camera) measured in world units
17 public float
Range
= 1.0f;
18
19 //Amount of ammo remaining (-1 = infinite)
20 public int
Ammo
= -1;
21
22 //Recovery delay
23 //Amount of time in seconds before weapon can be used again
24 public float
RecoveryDelay
= 0.0f;
25
26 //Has this weapon been collected?
27 public bool Collected = false;
28
29 //Is this weapon currently equipped on player
30 public bool IsEquipped = false;
31
32 //Can this weapon be fired
33 public bool CanFire = true;
34
35 //Next weapon in cycle
36 public Weapon NextWeapon = null;
37 }
Line 05.
Notice that practically any class definition in Unity always involves
inheritance. Even our abstract base class
Weapon
derives from
MonoBehaviour
,
a Unity API class used as a base for
Components
. Other weapon classes, such
as
Fists/Punch
and
Gun
will derive from
Weapon
. This means there are multiple
chains of inheritance happening here:
Guns
➤
Weapon
➤
MonoBehaviour
. And
even
MonoBehaviour
derives from
Behaviour
, which derives from
Component
,
which finally derives from
Object
—an ultimate ancestor class.