- Home /
Time.deltaTime stops counting up, after the Player is destroyed
Hi there,
I'm trying to make a Script, which must reload the Level, after 2,7 seconds, after the Player dies by falling off-screen. However, as soon as the GameObject is destroyed, Time.deltaTime stops counting up. How can I solve this problem?
Code:
using UnityEngine;
using System.Collections;
public class FallDeath : MonoBehaviour {
public GameObject player;
private float startTime = 0.0f;
void Update () {
if (player.transform.position.y < -5) {
startTime += Time.deltaTime;
Destroy(player);
audio.Play();
if (startTime > 2.7f)
Application.LoadLevel(Application.loadedLevel);
Debug.Log(startTime);
}
}
}
Answer by Dave-Carlile · Mar 07, 2013 at 09:43 PM
If the script is attached to the player object then destroying the player destroys the script. It doesn't look like you need to actually destroy the player object since the call to Application.LoadLevel will do that for you.
From the documentation:
"When loading a new level all game objects that have been loaded before are destroyed."
Here's updated code that shows how to play the audio once, then wait for the timer. Not tested, so you may need to tweak it some.
public class FallDeath : MonoBehaviour
{
public GameObject player;
private float startTime = 0.0f;
bool waiting;
void Update()
{
// if the player is off the map, and we haven't already started waiting for the level load...
if (player.transform.position.y < -5 && !waiting)
{
// play the audio - only want to do this want
audio.Play();
// set a flag indicating that we're waiting
waiting = true;
}
// if we're waiting then update the timer, load level after 2.7 seconds
if (waiting)
{
startTime += Time.deltaTime;
if (startTime > 2.7f)
{
Application.LoadLevel(Application.loadedLevel);
}
}
}
}
Ah - that's because when you don't destroy the player the script continues running each frame, so you're calling audio.Play over and over. I'll edit my answer with a way to handle that...
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How would you make your player freeze for a certain amount of time? 2 Answers
How to call a routine every 3 seconds? 2 Answers
Reload level after timer hits 0 1 Answer
Creating a Timer 0 Answers