- Home /
Keeping a float variable within a range based on keyboard input
Hi guys, does anyone know haw to keep a float value within a range. Basically the code i have uses an if(Input.GetKey(KeyCode.E) then increment a float variable by 1, however i want to keep the variable within the range of 0 and 100. There is also an if(Input.GetKey(KeyCode.Q) that will decrement the same float by 1. The inputs are held in the update method.
When the user releases the an input key the variable will be stored in a hastable aassigned a different key value based on how long it takes for the user to release the input.
For example the user will hold down E for 5 seconds and 10 will be recorded in the float variable and inserted into the hashtable with its own key. The next time they press E it will perform the same procedure , except unless its found the same key it will add its own key and value. The summation of all values in the hashtable should only be at max 100 and not less than zero.
Thank you
Answer by Berenger · Mar 07, 2012 at 11:56 PM
To keep a float value within a range, use Mathf.Clamp. To sample the imput every x seconds, it's a coroutine with an infinite loop and a yield WiatForSeconds(x).
hi berenger, what do you meean by coroutine , i dont fully understand what that is? sorry im a little new to unity . So do you mean after each time i increment the float variable i have a coroutine to check that the variable is within range 0<= x <= 100.
Your answer
Follow this Question
Related Questions
[Math] Projection of a Number onto a given Number Range. 1 Answer
Rigidbody with Accelerometer 2 Answers
Input and applying physics, Update or FixedUpdate? 3 Answers
input not working on high framerate 0 Answers
How to generate a Random Float Variable 4 Answers