-4
\$\begingroup\$

I really can't spot the error, or the misspelling. This script should increase the variable currentTime with 1 every second, as long as i am holding the Space button down.

This is Unity C#.

using UnityEngine;
using System.Collections;

public class GameTimer : MonoBehaviour {

    //Timer
    private bool isTimeDone;
    public GUIText counter;
    public int currentTime;
    private bool starting;

    //Each message will be shown random each 20 seconds.
    public string[] messages;
    public GUIText msg;

    //To check if this is the end
    private bool end;

    void Update () {
        counter.guiText.text = currentTime.ToString();

        if(Input.GetKey(KeyCode.Space)) {
            if(starting == false) {
                starting = true;    
            }

            if(end == false) {
                if(isTimeDone) {
                    StartCoroutine(timer());
                }
            } else {
                msg.guiText.text = "You think you can do better? Press 'R' to Try again!";
                if(Input.GetKeyDown(KeyCode.R)) {
                    Application.LoadLevel(Application.loadedLevel); 
                }
            }
        }

        if(!Input.GetKey(KeyCode.Space) & starting) {
            end = true; 
        }
    }

    IEnumerator timer() {
        isTimeDone = false;
        yield return new WaitForSeconds(1);
        currentTime++;
        isTimeDone = true;
    }

}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Err, what's wrong exactly? Doesn't compile? Doesn't run? Gives wrong result? \$\endgroup\$ Nov 12, 2012 at 16:47

2 Answers 2

1
\$\begingroup\$

Unless there's other ocde you're not showing us, isTimeDone is never initialized to true (bools are false by default), so your StartCoroutine(timer()); never gets called.

When you're running into issues like this, the best thing to do is attach the debugger to it. Barring that, put debug prints on lines you think should be getting hit with the values of variables as they currently are so you can see the program flow.

\$\endgroup\$
0
\$\begingroup\$

Well I'm not exactly sure what `StartCoroutine` does (I assume it is a form of asynchronous function execution) so I'll skip that. It looks like your problems stem from the fact that you never set `starting` back to false. You should probably add that to your second if statement.

On top of that. you never actually set the value `isTimeDone` to true outside of the method that only gets called inside the if statement that relies on the true value. You should initialize this value to true in your behaviors constructor.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .