For and While loop crashing unity and system
i'm trying to write the code for the pistol to generate a bullet every 2 seconds once its instantiated so i used this code
public class Pistol : MonoBehaviour { int BulletCounter; public GameObject bullet; public GameObject WhereToSpawn; int i; // Use this for initialization void Start () {
while (gameObject.activeSelf == true)
{
bullet = (GameObject)Instantiate(bullet, WhereToSpawn.transform.position, Quaternion.identity);
new WaitForSeconds (2);
}
}
problem is this crashes my entire system when i try to play it. what should i do?
Answer by ScaniX · Sep 10, 2016 at 06:29 PM
Your code consists of an endless loop. Unity is waiting for it to finish... forever...
You need to understand how those callback methods of MonoBehaviours work. They are callbacks that get invoked when an event occurred, an object is initialized or in a repeated pattern (per frame or in a certain interval).
You should never add code to those methods that is taking long (or even forever) to finish. If you need something like this, you can create a coroutine. In your case I think you will be better off without one.
public class Pistol : MonoBehaviour {
int BulletCounter;
public GameObject bullet;
public GameObject WhereToSpawn;
int i;
float lastSpawnTime;
// Use this for initialization
void Start () {
lastSpawnTime = Time.time;
}
void Update() {
if (Time.time - lastSpawnTime > 2) {
bullet = (GameObject)Instantiate(bullet, WhereToSpawn.transform.position, Quaternion.identity);
lastSpawnTime = Time.time;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612092526im_/https://answers.unity.com/themes/thub/images/avi.jpg)