add to an int on keypress
why is this not working? seems so simple. every time the E key is pressed I want to add 1 to my public int. But it goes from 0 to 4, then 8, then 6 then 10. seemingly random even values with no particular rhyme or reason
public AudioClip beep;
public int mode = 0;
void OnTriggerStay(Collider other) {
if(other.tag == "Player")
{
if (Input.GetKeyDown(KeyCode.E))
{
audio.PlayOneShot(beep);
mode += 1;
}
Answer by Bradybeast128 · Sep 09, 2017 at 01:54 AM
If you want to only add one to the int once than just switch mode += 1;
to mode =+ 1;
I hope that helps, if you want to continually add once every time E is pressed, than your out of luck because I'm having the same problem and couldn't find the answer anywhere.
Answer by shadowpuppet · Sep 09, 2017 at 02:09 AM
actually , a similar problem occurs in a few of my other scripts as if it is registering the keydown more than once. I worked around it by adding an additional condition . So after it adds the 1 ( because adding is true) the next task it performs is making adding false
void OnTriggerStay(Collider other) {
if(other.tag == "Player")
{
if (Input.GetKeyDown(KeyCode.E))
{ Debug.Log ("true"); adding =true; { if (adding ==true )
{ audio.PlayOneShot(beep); mode += 1; adding = false; Debug.Log ("false"); } }
@shadowpuppet can you explain to me why you have "adding" in there. I tried it and the console says adding does not exist in its current context. here's my code incase it would help: void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("healthpotion")) { if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E)) adding =true; { if (adding == true) { healthpotions = +1; adding = false; } Destroy(other.gameObject); } }
"adding" is just a boolean. just add that to the top of the script. It's purpose is that it needs to be true AND in the trigger zone AND keydown E to add points. once the points are added, the next line executes making adding false so the 3 conditions required to add points are no longer met so no more points added. I haven't tested it but it's identical to the way I do a few other things so should work. By making it public you can actually see in the inspector if it gets ticked on and off
using UnityEngine;
using System.Collections;
public class addingScript : $$anonymous$$onoBehaviour {
public bool adding;
void OnTriggerStay(Collider other) { if(other.tag == "Player") { if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E)) adding =true; { if (adding ==true )
{ audio.PlayOneShot(beep); mode += 1; adding = false; } } }
the whole thing with debug added
using UnityEngine;
using System.Collections;
public class addingScript : $$anonymous$$onoBehaviour {
public bool adding;
void OnTriggerStay(Collider other) {
if(other.tag == "Player")
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
adding =true;
Debug.Log ("true");
{
if (adding ==true )
{
audio.PlayOneShot(beep);
mode += 1;
adding = false;
Debug.Log ("false");
}
}
}