Game Development Reference
In-Depth Information
Completing the Punch and Gun Weapons
The PlayerController has been sufficiently prepared and modified to support weapon switching.
It's now time to update the two weapon classes themselves to support this behavior. Doing this is
required because the PlayerController.EquipNextWeapon method calls on an Equip function in the
Weapon class, to equip the weapon for the Player (line 172). This method is invoked not on the Weapon
class itself, but by using a SendMessage function, allowing the derived classes to respond. And it's
called for any newly equipped weapon, each and every time it's equipped, giving it the opportunity
to perform any initialization code, such as displaying the default, idle sprite. Listing 6-8 lists the
completed Weapon_Punch code, with additions highlighted in bold.
Listing 6-8. Weapon_Punch.cs: Completed Punch Weapon
001 //------------------------------------------------
002 using UnityEngine;
003 using System.Collections;
004 //------------------------------------------------
005 //Inherits from Weapon class
006 public class Weapon_Punch : Weapon
007 {
008 //------------------------------------------------
009 //Default Sprite to show for weapon when active and not attacking
010 public SpriteRenderer DefaultSprite = null;
011
012 //Sound to play on attack
013 public AudioClip WeaponAudio = null;
014
015 //Audio Source for sound playback
016 private AudioSource SFX = null;
017
018 //Reference to all child sprite renderers for this weapon
019 private SpriteRenderer[] WeaponSprites = null;
020 //------------------------------------------------
021 void Start()
022 {
023 //Find sound object in scene
024 GameObject SoundsObject = GameObject.FindGameObjectWithTag("sounds");
025
026 //If no sound object, then exit
027 if(SoundsObject == null) return;
028
029 //Get audio source component for sfx
030 SFX = SoundsObject.GetComponent<AudioSource>();
031
032 //Get all child sprite renderers for weapon
033 WeaponSprites = gameObject.GetComponentsInChildren<SpriteRenderer>();
034
035 //Register weapon for weapon change events
036 GameManager.Notifications.AddListener(this, "WeaponChange");
037 }
 
Search WWH ::




Custom Search