I want a timer to start when my rocket takes off and stop when it lands. Stopping works fine (using a collider and state-switching) but I can't get the timer to start when I press the boost button.
Currently the timer text is displayed at the moment I pressed the button but clearly has been counting from the moment the scene started, not the moment the button is pressed.
Any help will be greatly appreciated. If there is a better way to start the timer rather than when I press the boost button then I am open to ideas!
Here is the all relevant code (I think). It appears as though it should be working to me, but it isn't.
// Timer
public Text timerText;
private float startTime;
private bool started = false;
private bool finished = false;
void Start ()
{
startTime = Time.time; // get time since scene started
}
void Update ()
{
if (currentState == State.Alive)
{
ProcessBoostInput();
ProcessRotationInput();
ProcessFiringInput();
if (started)
{
RunTimer();
}
}
}
private void ProcessBoostInput()
{
if (Input.GetKey(KeyCode.A) || (CrossPlatformInputManager.GetButton("Fire1")))
{
BoostShip();
PlayBoostSound();
if (started != true)
{
started = true;
}
}
private void RunTimer()
{
if (finished)
{
return;
}
else if (started)
{
float timeSinceTimerStart = Time.time - startTime;
string minutes = ((int)timeSinceTimerStart / 60).ToString();
string seconds = (timeSinceTimerStart % 60).ToString("f3");
timerText.text = minutes + ":" + seconds;
}
}
private void StopTimer()
{
finished = true;
timerText.color = Color.green;
}