My script keeps crashing my Unity Editor Client. Please help
So I created this script recently to spawn a "enemyPrefab" every x seconds. But when the function is called on my Unity client just crashes and I have to open up Task Manager and manually End Task it for it to close.
Here's my script:
#pragma strict
//Variable list
public var spawner : Transform[];
public var spawnTime : float;
public var enemyPrefab : GameObject;
private var spawner_num : int;
function Start ()
{
//Call the SpawnEnemy function every spawnTime seconds
InvokeRepeating ("SpawnEnemy", spawnTime, spawnTime);
}
function SpawnEnemy ()
{
//Tells the log that the function has been called upon
Debug.Log("Started");
while (true)
{
//Picks a random spawner to spawn "enemyPrefab" out of
spawner_num = Random.Range(0,3);
//Tells log what spawner has been picked
Debug.Log("Spawner is spawner number " + spawner_num);
//Spawns the "enemyPrefab" at the spawner location
Instantiate(enemyPrefab, spawner[spawner_num].position, spawner[spawner_num].rotation );
}
//Tells the log the function has ended.
Debug.Log("Ended");
}
Thank you so much if you can help me out on this, I've been trying to advance my game for about 30 minutes now googling this topic but can't find the answer, but anything helps! :) (P.S. I'm on Windows if that helps any.)
Answer by ElijahShadbolt · Dec 18, 2016 at 08:27 AM
Get rid of the while loop! while(true)
goes on forever without stopping, since there are no yield or break statements inside the loop.
The InvokeRepeating()
function already handles the looping (since it calls SpawnEnemy()
every spawnTime
seconds), so there is no need for a loop inside your function.
Oh! You're right, that's probably spiraling my script out of control, I'll try it right now! Thanks for the help. I'm still quite new to coding so I'll make sure to remember this next time lol!
So I tried this and the script seems more clean but my client still stops responding, could it just be something wrong with my client or computer then?
Answer by sandpixels · Dec 18, 2016 at 10:52 AM
I found my issue, my Firewall was interfering with my Editor and crashing it for some reason, moved around some permission and now I could do it safely! @SublimeGamer Thanks for telling me about the while loop ahead of time! It helped alot ;D
Your answer
![](https://koobas.hobune.stream/wayback/20220612102947im_/https://answers.unity.com/themes/thub/images/avi.jpg)