- Home /
Questions about a Weapon Switch script.
using UnityEngine;
public class SwitchMethodOne : MonoBehaviour {
public GameObject currentWeapon;
public GameObject[] myWeapons = new GameObject[]
public int currentWeaponIndex = 0;
public void Awake() {
myWeapons = new GameObject[Enum.GetValue(typeof(myWeapons)).Length];
}
void Update() {
if(Input.GetButtonDown("KeyCode.LeftShift")) {
currentWeaponIndex = (currentWeaponIndex + 1) % myWeapons.Length;
currentWeapon = weaponArray[currentWeaponIndex];
Questions:
What is the purpose of "(currentWeaponIndex + 1) % myWeapons.Length;?"
. Currently, "currentWeaponsIndex" is equal to 0, so why are we just adding 1 to it?
(In reference to first question) why are we getting the remainder of 1/myWeapons.Length? . "% myWeapons.Length;"
Answer by Habitablaba · Oct 31, 2014 at 10:41 PM
What is happening here, is a bit of error checking and defensive programming. It makes it so the user cannot select a weapon out of range of the weapon collection, instead it loops around the list. So if the user is at the end of the list and presses shift, they go to the first weapon.
The mod operator (%) is a great way to make sure a value stays within the bounds of another value.
So is it safe to say that for question 1, the (%) is like saying "of?"
Increment up until you reach the limit of myWeapons.Length
And I thought (%) meant take the remainder of the two values you're diving. So say we have two guns, would it be 1/2?
it is taking the remainder! But it is also being super awesome. Check it out:
assume length = 3 and current index = 0;
[press shift]
0 + 1 = 1
1 / 3 = 0, R 1
index = 1;
[press shift]
1 + 1 = 2
2 / 3 = 0, R 2
index = 2;
[press shift]
2 + 1 = 3
3 / 3 = 1, R 0
index = 0; // this is the cool part. Now we're back at the start.
it has the added benefit of a bit of error checking. Let's assume index gets all crazy and out of bounds.
assume length = 3 and current index = 4;
[press shift]
4 + 1 = 5
5 / 3 = 1, R 2
index = 2; // neat!
Your answer
Follow this Question
Related Questions
Wrong object always Instantiated 1 Answer
Read different game objects into array at same time? 2 Answers
How to make an array list set to false gradually instead of instantly? 2 Answers
Multidimensional arrays - editing one element within one of the arrays 1 Answer
rotating vertices with for loop in 0 Answers