Sunday, July 5, 2015

Tutorial: Weapon Change

One of the most key components of modern day FPS and 3rd person shooters as well as hack and slash like Diablo has been the ability to change weapons. Today's tutorial will be about changing weapons. It will be simple, we will have slots for three weapons. Press the numbers 1-3 to change.



Before we begin we need to first set up our character. If you haven't already place the FPS controller in the scene. Add an empty GameObject and position it approximately where you would hold a weapon, parent the empty GameObject to the MainCamera. Rename this empty object to: weaponsObject. Now add an AudioSource to the weaponsObject. Check off Play on Wake.



For this script we only need two variables. An array that will hold the GameObjects that correspond to our weapons: GameObject[] weapon An AudioClip to play a sound when we switch weapons: AudioClip switchWeapon

Now in the update we will set our structure to receive user input, based on the number they choose we will call a function to change our weapon and play a sound.
if(Input.GetKeyDown(KeyCode.Alpha1))//Alpha1 means the numbers that are above the letters. No the function keys.
{
changeWeapon(1);
GetComponent<AudioSource>().PlayOneShot(switchWeapon, 0.4f);
}

So we are checking if they player pressed a key. Alpha keys are the numbers above you letters, using the keypad will not be recognized. Now based on weathers its 1,2,3 we pass the integer value to the changeWeapon(); function. We will play it once(PlayOneShot) and at a voulme of 0.4f.
Now copy past the above code twice change the ones to twos and threes respectively.

The changeWeapon() function operates on a loop using a makeshift break; statement. We pass the integer value based on the number the user presses, We compare it in the for loop. If the for loop variable (i) matches the passed value we set that weapon active.

public void changeWeapon(int num)
{
     for(int i = 1; i < weapon.Length; i++)
{
if(i == num)
weapon[i].gameObject.SetActive(true);
else
weapon[i].gameObject.SetActive(false);
}
}

Drive Link:

Change Weapon.cs

No comments:

Post a Comment