commands.close.hint.6
continue something if a key is still pressed down?
I'm trying to basically get this script to check (every frame) that the key is held down to run the if-then statements.currently it only checks on the frame that the button is pushed. I am wanting it to check every 3 seconds to run the if-then statements if someone could help me get started with that as well.
using UnityEngine;
using System.Collections;
public class RandomBattles : MonoBehaviour {
private int RandNum;
public bool InBattle;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RandNum = Random.Range(1, 1000);
if (Input.GetKeyDown(KeyCode.W)||Input.GetKeyDown(KeyCode.S)){
if(RandNum > 1){
if(RandNum < 1000){
inBattle ();
}
}
}
}
void inBattle () {
Debug.Log ("battle");
}
}
Answer by aldonaletto · Oct 10, 2013 at 07:57 PM
Use GetKey instead of GetKeyDown: GetKey returns true while the key is pressed.
that has solved that problem, any ideas on how i can keep track of the seconds that have passed, but only when the button is pressed down?
When "On$$anonymous$$eyDown" record the time in a float variable with "Time.time". During the "On$$anonymous$$ey" event check when to stop action by comparing recorded time to current time (Time.time).
As @Doreith said, you can use the Get$$anonymous$$eyDown and Get$$anonymous$$eyUp functions just to control start/stop ti$$anonymous$$g:
float startTime; // declare this outside any function
void Update () {
if (Input.Get$$anonymous$$eyDown("w")||Input.Get$$anonymous$$eyDown("s")){
// key pressed: save the current time
startTime = Time.time;
}
if (Input.Get$$anonymous$$eyUp("w")||Input.Get$$anonymous$$eyDown("s")){
// key released: measure the time
float timePressed = Time.time - startTime;
// do here whatever you want with timePressed
}
RandNum = Random.Range(1, 1000);
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W) || Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.S)){
if(RandNum > 1){
if(RandNum < 1000){
inBattle ();
}
}
}
}
i actually had that all set up shortly after his response, thank you (:
Follow this Question
Related Questions
Unity keeps crashing when 'While' is used... 1 Answer
Input script 1 Answer
Weirdest coroutine crash ever 1 Answer
Keystore Problem 0 Answers
Coroutine, while, and Waitforseconds 1 Answer