- Home /
The question is answered, right answer was accepted
Unity crashes when running the following code
I'm trying to spawn a number of object flying over the screen from left to right. I'm using the follow code:
public Vector2 o;
public float timeLeft = 1f;
public GameObject irri;
void FixedUpdate ()
{
o = irri.rigidbody2D.velocity;
o.x = -2;
irri.rigidbody2D.velocity = o;
}
IEnumerator Spawn2()
{
while (timeLeft > 0)
{
if (syanMode == 1)
{
Vector3 spawnPosition2 = new Vector3 (2.0f, Random.Range (0, 0.5f), 0.0f);
Instantiate (irri, spawnPosition2, Quaternion.Euler(0.0f, 0.0f, Random.Range(0.0f, 360.0f)));
yield return new WaitForSeconds ( Random.Range (0.1f, 0.5f));
}
}
}
I have created an asset that has a rigidbody2d and a sprite, and assigned that to the variable irri in the scene.
as soon as I hit play to test if it works, unity freezes. why is that?
That helped! It's not spawning any objects now tho.. (I'm 100 % sure syanmode = 1)
Am I right in saying WaitForSeconds work in integers only?
Is Random.Range 0.1f possibly rounding down?
Does WaitForSeconds(0) work?
That helped! It's not spawning any objects now tho.. (I'm 100 % sure syanmode = 1)
Do you refer to @gjf comment?
Answer by gjf · Nov 26, 2014 at 08:13 PM
You need to yield if the 'if' isn't executed
yeah. had to put yield return in there. now it looks like this:
IEnumerator Spawn2()
{
while (timeLeft >= 0)
{
if (syan$$anonymous$$ode == 1)
{
Vector3 spawnPosition2 = new Vector3 (2.0f, Random.Range (0, 0.5f), 0.0f);
Instantiate (irri, spawnPosition2, Quaternion.Euler(0.0f, 0.0f, Random.Range(0.0f, 360.0f)));
yield return new WaitForSeconds ( Random.Range (0.1f, 0.5f));
}
yield return new WaitForSeconds (0.0f);
}
}
still no objects tho.
But it fixed the crash.
QA solved, followup quetions in a fresh QA please.
Answer by johne5 · Nov 26, 2014 at 08:31 PM
I don't see where you're changing timeLeft to be less then 0, you might try timeLeft >= 0.
So the while loop is stuck in the loop
It usually doesn't hurt being stuck in a while loop when executing a coroutine. However you have to invoke a yield return each iteration or you're really stuck inside the while loop doing nothing else.