- Home /
Question by
East Midnight Studios · Jul 08, 2014 at 02:47 PM ·
crashspawntimerfreeze
Timer Spawn Freezing Unity C#
Whenever I run the code to spawn my asteroids after a certain amount of seconds at predefined locations, Unity always freezes on me! I don't know what is wrong with the code, there is no errors, it just waits for the 4 seconds and then freezes. Help!
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
private PlayerLevel level;
public float timer = 1f;
public float secondsToWait= 4f;
public float totalSeconds;
public Transform[] spawn;
public GameObject asteriod;
void Start () {
level = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerLevel> ();
}
void Update (){
int spawnNumber = Random.Range (0, 1);
if (totalSeconds <= secondsToWait) {
if (timer > 0) {
timer -= Time.deltaTime;
}
else if (timer <= 0) {
totalSeconds++;
timer = 1f;
while (level.level >= 1) {
if (totalSeconds == 4f) {
Instantiate (asteriod, spawn [spawnNumber].position, spawn [spawnNumber].rotation);
secondsToWait = 4f;
}
}
while (level.level >= 5) {
if (totalSeconds == 2f) {
Instantiate (asteriod, spawn [spawnNumber].position, spawn [spawnNumber].rotation);
secondsToWait = 2f;
}
}
while (level.level >= 10) {
if (totalSeconds == 1f) {
Instantiate (asteriod, spawn [spawnNumber].position, spawn [spawnNumber].rotation);
secondsToWait = 1f;
}
}
while (level.level >= 15) {
if (totalSeconds == 0.5f) {
Instantiate (asteriod, spawn [spawnNumber].position, spawn [spawnNumber].rotation);
secondsToWait = 0.5f;
}
}
}
}
}
}
Thanks in Advance,
Nick
Comment
@Harshad$$anonymous$$ is right, yield out or break out, update is ran every frame, why do you need a while loop in your update? change your while to if statements and let it fall through after doing the spawning, let it do it's thing the next frame. Could also setup a timed invoke while in game.
Answer by Gizmoi · Jul 08, 2014 at 02:58 PM
Change your 'while' loops to 'if' conditions. Should fix it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613153527im_/https://answers.unity.com/themes/thub/images/avi.jpg)