- Home /
Code executing multiple times?
OK, I have a problem
Let's say I have 2 items in an inventory and I use 1. I should now have 1. But for some reason, my code will execute the action of taking away 1 multiple time during a button press, leaving me with no items
My Code:
//quick select use//
if (quickItemNumber == 0) { Destroy(quickButton.gameObject); }
if (quickItemNumber >= 1)
{
if (quickButton.GetComponent<ButtonMaster>().itemID == "001")
{
gameManager.GetComponent<InventoryManager>().item001 -= 1f;
}
}
My question is; How can I make this code happen only once?
Thanks for your help
How are you handling the button press? If you're using "Input.Get$$anonymous$$ey()," it will fire every update the key is held down. $$anonymous$$ake sure you're using "Input.Get$$anonymous$$eyDown()" or "Input.Get$$anonymous$$eyUp()".
https://docs.unity3d.com/ScriptReference/Input.html
I'm using Input.GetAxis, as it is a PS4 d-pad.
Answer by c_Feng · Jan 06, 2019 at 12:09 AM
Your button input is being registered each time the code is run. To get around this, implement a boolean check:
bool buttonHeld = false;
if (Input.GetAxis(<blahblah>))
{
if (!buttonHeld)
{
buttonHeld = true;
// Execute input code (use item)
}
}
else
{
buttonHeld = false;
}
You're a life-saver my dude. Worked beautifully. Thank you so much.