- Home /
Increasing value by one every second, if right arrow is pressed - C#
Hello, I have a float "Levelint" and I want to increase it by one while I am holding the right arrow. So, when I hold the right arrow it will increase by one, every second, and if I just press the right arrow, to just add one, once.
Does anyone know how to do this? Any help would be appreciated, thanks!
If the question doesn't make sense, let me know and I can try to explain it better.
Answer by toddisarockstar · Aug 04, 2017 at 08:31 PM
public int Levelint;
private float timer;
void Update(){
if(Input.GetKeyDown("right")){timer=0; Levelint++;}
if(Input.GetKey("right")){timer+=Time.deltaTime;
if(timer>1){timer-=1;Levelint++;}}
}
Answer by Timo326 · Aug 04, 2017 at 08:00 PM
private float Levelint;
private int lastTimeInt = -1;
void Update()
{
If (Input.GetKey(KeyCode.ArrowRight)) // i am not sure if it is ArrowRight
{
If ((int)Time.time > lastTimeInt) Levelint++;
lastTimeInt = (int)Time.time;
}
else If (Input.GetKey(KeyCode.ArrowRight)) // i am not sure if it is ArrowRight
{
LastTimeInt = -1;
}
}
Oh it can happen that you increase two times within the first second. To avoid this, check if at least one complete second has passed before the second increase is done.
Answer by Shrikky23 · Aug 04, 2017 at 10:45 PM
I will give you psuedo code,
Based on Key press, set isPressed bool value to true;
in update, if isPressed is true, increase a timer counter += Deltatime,
If counter > 1 , change level / do what you want to do, reset counter to 0.
If isPressed becomes false, change counter to 0.
Your answer
Follow this Question
Related Questions
Key for GUI.Button 2 Answers
Distribute terrain in zones 3 Answers
If button held 3 seconds do something 1 Answer
How to push down a button and hold it through script? 0 Answers
Multiple Cars not working 1 Answer