Game Development Reference
In-Depth Information
178 //------------------------------------------------
179 //Event called when ammo expires
180 public void AmmoExpired(Component Sender)
181 {
182 //Ammo expired for this weapon. Equip next
183 EquipNextWeapon();
184 }
185 //------------------------------------------------
186 }
Lines 40 and 43.
There are some important features in this code. First, notice
that
PlayerController
supports weapon switching between both weapon
types, and yet it never references any one of the derived classes directly, either
Weapon_Punch
or
Weapon_Gun
. It uses the super-class
Weapon
to reference weapon
objects.
Lines 160-185.
This is where the core functionality of weapon-switching occurs.
When the gamer presses the period (.) key on the keyboard, and is carrying
more than one eligible weapon, the active weapon is switched to the next. This
is achieved using the
NextWeapon
variable coded into the
Weapon
class. This
value should be specified in the Object Inspector for all weapons, allowing any
weapon to reference the next weapon in the cycle. For our purposes, the punch
weapon refers to the gun as its next. And further, because we wanted to cycle
around the weapons in a loop, the gun refers back to the punch weapon as its
next. But notice again (lines 169 and 175) that the
EquipNextWeapon
function
works with the
Weapon
super-class and not any of its derivatives.
Both comments for Listing 6-7 point to
polymorphism
at work. In short, whenever multiple classes
derive from a common ancestor class using
inheritance
, such as the weapon classes deriving from
Weapon
, you can still loop through and work with those classes together by using only references
to their base or ancestor class (see lines 166-176). This means that
PlayerController
can
maintain a complete array of different weapon types, using only the base type
Weapon
. Because
of
polymorphism
, C# sees only the
commonalities
between these classes through their ancestor,
seeing them as being fundamentally alike and interchangeable, and it ignores their differences
implemented from deriving. The practical value of this means that many different objects, regardless
of their type, can be treated alike if they share a common ancestor class somewhere in their lineage.
It becomes possible to loop through and iterate over objects of multiple types stored together in a
single array of only one type.
Note
For more information on polymorphism, see the MSDN C# documentation at