Switching items - can't detect a crazy loop that is happening.
So, I'm trying to switch weapons in my game. The player has 3 different ones. Each weapon has an ID that I use to detect wich weapon is active and I call the method to switch weapons when the player presses the "X" key.
if (Input.GetKey(KeyCode.X))
{
ChangeWeapons();
}
This is the method (please, ignore the horrible hard coded parts haha.)
void ChangeWeapons()
{
if (mCurrentWeapon == 1 | mCurrentWeapon == 0)
{
mCurrentWeapon++;
}
else if (mCurrentWeapon == 2)
{
mCurrentWeapon--;
}
switch (mCurrentWeapon)
{
case 0:
mWeapons[0].GetComponent<MeshRenderer>().enabled = true;
mWeapons[1].GetComponent<MeshRenderer>().enabled = false;
mWeapons[2].GetComponent<MeshRenderer>().enabled = false;
break;
case 1:
mWeapons[1].GetComponent<MeshRenderer>().enabled = true;
mWeapons[0].GetComponent<MeshRenderer>().enabled = false;
mWeapons[2].GetComponent<MeshRenderer>().enabled = false;
break;
case 2:
mWeapons[2].GetComponent<MeshRenderer>().enabled = true;
mWeapons[0].GetComponent<MeshRenderer>().enabled = false;
mWeapons[1].GetComponent<MeshRenderer>().enabled = false;
break;
}
}
What is happening is a crazy loop that changes the weapons three or four times at once. I need to fix this. Any suggestions? Thanks for the attention in advance.
Answer by phil_me_up · Mar 11, 2016 at 01:48 PM
You might want to look here: http://docs.unity3d.com/ScriptReference/Input.html
The 'GetKey()' method will return true whilst a key is held down, so unless you tap and release the key within the space of one frame (assuming you're checking in the Update loop), you will be calling Change Weapon a lot.
You probably want to switch to GetKeyUp or GetKeyDown
@mvpires :
Just as an added note, you might want to do the rest something like this :
$$anonymous$$eshRenderer[] weapons;
int currentWeapon;
void ChangeWeapon()
{
currentWeapon++;
if(currentWeapon >= weapons.Length) currentWeapon = 0;
for(int i = 0; i < weapons.Length; i++)
{
if(i == currentWeapon) weapons[i].enabled = true;
else weapons[i].enabled = false;
}
}
Your answer
Follow this Question
Related Questions
Picked up items being added multiple times on the inventory list. 1 Answer
Scene Switching problem. Scene becomes black when it changes 2 Answers
Switch between 5 cameras in the game by clicking. 0 Answers
How I can count how many time gameOver scene is loaded ? 1 Answer
How to Switch GameObjects (Weapons) by reaching a specific amount of score? 0 Answers