- Home /
Why is my script still running in other scenes?
Ok, so I have 3 scenes in my game, Menu, Level 1, and Game Over. The script below is an asteroid spawning system that gets increasingly harder as you go. When the player dies and the game switches over to the Game Over scene the script keeps running. So when the player restarts the level the game is super hard. I have no DontDestroyOnLoad things in my game and no static variables. I dont know why its doing this but is there any way to stop the script and reset it when the level is re played?
#pragma strict
var prefab : GameObject;
var nextActionTime = 0.0f;
var period = 0.7f;
function Update() {
period -= Time.deltaTime * (0.006 / 0.5);
if (Time.time > nextActionTime) {
nextActionTime += period;
var position: Vector3 = Vector3(Random.Range(-1.8, 2), 0, Random.Range(-1.8, 2));
Instantiate(prefab, position, Quaternion.identity);
}}
Answer by rutter · Jul 12, 2014 at 04:19 AM
It's not that the script keeps running, it's that you're using Time.time in a peculiar way.
Remember that Time.time
is the number of seconds since the application started running. If your game has been running for 500 seconds -- no matter which level(s) you've been on -- then Time.time
will be 500
.
Because your nextActionTime
value starts counting from 0
, and increments by period
each time you spawn an asteroid, you might end up spawning one asteroid per frame once Time.time
gets to be a big number.
How to fix this? Fix your time tracking! :)
First option: instead of having nextActionTime
count from zero, set it to Time.time + period
once the level loads. You could do this in Awake() or Start().
Second option: instead of using Time.time
, use Time.timeSinceLevelLoad, which is the number of seconds since you last loaded a scene.
Thanks man! I knew it would be some simple thing like that. Your a life saver! :)
Your answer
Follow this Question
Related Questions
Disable GameObject Only Father Not Children 2 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
How Do I Make A Health Bar 6 Answers
Pause Menu background problem 0 Answers