- Home /
Unity sometimes crashes when playing the scene.
I have no idea why my code doesn't work. I've tried with all the combinations of game objects and my GameController couses of the problem.
It basicly adds grabber objects inside a circle randomly and tries to make them far from each other.
The code is here (C#):
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
//public int playerNum = 1;
//public bool classic = true;
public GameObject Grabber;
public float spawnWait=0;
public float startWait=1.5f;
public int maxGrabberNum = 5;
public float minGrabberDist = 2f;
void Start ()
{
StartCoroutine (SpawnGrabbers ());
}
IEnumerator SpawnGrabbers ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
Debug.Log("In da first while loop");
GameObject[] grabbers = GameObject.FindGameObjectsWithTag("Grabber");
if(grabbers.Length<maxGrabberNum)
{
Debug.Log("not enought grabber, we need more!!!");
Vector3 pos;
Vector2 rnd;
float dist=1000f;
float mgni;
do
{
Debug.Log("In da do while");
rnd = Random.insideUnitCircle*12f;
pos = new Vector3(rnd.x, rnd.y, 0);
for(int i=0;i<grabbers.Length;i++)
{
Debug.Log("In da for loop, index is: "+i+"/"+grabbers.Length);
mgni = (grabbers[i].transform.position-pos).magnitude;
if(dist>mgni)
{
dist = mgni;
}
}
Debug.Log("min dist is: "+ dist);
}while(dist<minGrabberDist);
Debug.Log("end of the do-while loop");
Instantiate (Grabber, pos ,Quaternion.Euler(90,0,0));
}
Debug.Log("now we are waiting "+spawnWait+" seconds");
yield return new WaitForSeconds (spawnWait);
}
}
}
Maybe an endless loop is the problem.
My last Log is the: Now we are waiting 1.5 seconds.
In some cases it crashes, in others it doesn't.
I made a 'solution' like with adding a
yield return new WaitForSeconds (0.5f);
line at the end of the do-while loop, so basically this is where the problem occured.
Thanks Lewwwer, I just accidentally deleted a code that took me I guess an hour to make thinking that was the problem, and it wasn't this was. I should've read this sooner.
Your answer
Follow this Question
Related Questions
Unity not picking up errors until after reopening 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity crashes because of script 2 Answers
Unity3D MovieTexture Loop 0 Answers