Hi guys,
I really need some light on my task, because I’m a bit lost and don’t know what to do.
Here is a small sketch of my code
int x = 0;
int keyToPress = -1;
int fails = 0;
int correct = 0;
void MyFunc(){
if(x<=100){
int rand = Random.Range(0,1);
x++;
}
}
void Update(){
if (Input.GetKeyDown(KeyCode.A)){
if(keyToPress != 0){
fails++;
} else {
correct++;
}
}
if (Input.GetKeyDown(KeyCode.S)){
if(keyToPress != 1){
fails++;
} else {
correct++;
}
}
}
I want a way for MyFunc to be called every 3 seconds, but if after 1 second the user presses that key ‘A’ or ‘S’, I want to reset the timer and call MyFunc again until x == 100. I’m not sure what to use between those three methods or if there is another way.
Please help me
Odd considering the rand variable is confined to the scope of the if statement, therefore the MyFunc method is basically useless
To call MyFunc every 3 seconds you’d turn it into a coroutine like this:
IEnumerator myFuncRoutine;
IEnumerator MyFunc()
{
WaitForSeconds delay = new WaitForSeconds(3)
while(true)
{
// Algorithmy stuff to run every 3 seconds goes here
yield return delay;
}
}
This will run forever when called with:
myFuncRoutine = StartCoroutine(MyFunc);
Note that we’re keeping a reference to the routine in a global variable. You only need to do this for routines you want to stop later. For the second part, stopping it after 1 second if a key is pressed, you can do something like this:
float timeElapsed = 0;
void Update()
{
timeElapsed += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.S)
{
if (timeElapsed >= 1f)
{
StopCoroutine(myFuncRoutine);
timeElapsed = 0f;
}
}
if (Input.GetKeyDown(KeyCode.A)
{
if (timeElapsed >= 1f)
{
StopCoroutine(myFuncRoutine);
timeElapsed = 0f;
}
}
}
Here we’re keeping a float for the time elapsed, all you do is add Time.deltaTime (the duration of the last frame) to the total.