Issues Cycling Through Weapons-C#
I am trying to cycle through my weapons using the "F" key on my keyboard using the script below (@nastasache maybe you know how to fix this?). I currently only have two weapons that I'm trying to cycle through but when I run the code below, nothing happens.
public GameObject[] weapons;
public int currentWeapon = 0;
private int nrWeapons;
void Start () {
nrWeapons = weapons.Length;
SwitchWeapon (currentWeapon);
}
void Update () {
for (int i = 1; i <= nrWeapons; i++){
if (Input.GetKeyDown (KeyCode.F + i)) {
currentWeapon = i - 1;
SwitchWeapon (currentWeapon);
}
}
}
void SwitchWeapon (int index){
for (int i = 0; i < nrWeapons; i++) {
if (i == index) {
weapons [i].gameObject.SetActive (true);
} else {
weapons [i].gameObject.SetActive (false);
}
}
}
I've tried removing the "+ i" part of the if statement in the Update function so it just reads (KeyCode.F):
for (int i = 1; i <= nrWeapons; i++){
if (Input.GetKeyDown (KeyCode.F)) {
currentWeapon = i - 1;
SwitchWeapon (currentWeapon);
}
}
but this only lets me switch from my primary weapon to my secondary weapon a single time--I am not able to switch back to my primary weapon.
In the meantime I am going to set each weapon to a corresponding alpha key and have it switch that way but I would really love to have it cycle on a single key so if anybody is able to help or has any suggestions I'm all ears.
Thanks!!!
Answer by Mindmapfreak · Jun 23, 2016 at 06:29 PM
I am not sure what you are trying to do with the for-loop in Update. Changing the content of Update to
if (Input.GetKeyDown(KeyCode.F))
{
this.currentWeapon++;
if(this.currentWeapon>=this.nrWeapons)
{
this.currentWeapon = 0;
}
SwitchWeapon(this.currentWeapon);
}
should work.
Answer by Fperez418 · Jun 23, 2016 at 06:40 PM
YES!! Thank you @ChrisAngelMindmapfreak that was a huge help, it does exactly what you said it would!
Your answer
Follow this Question
Related Questions
Changing an objects location 1 Answer
Touch doesen´t work on Unity Remote, why? 0 Answers
I have error in my game saving script (C#). 1 Answer
PlayerPrefs mad?! 0 Answers
[Steamworks.NET] SteamAPI Problem help !,[Steamworks.NET] Problem 0 Answers