- Home /
I want to have a cannon that infinitely fires after a certain number of time but my script crashes unity
Idk how to make a script wait like you can in the c# virtual studio console and when I try to load my script from what I could gather infinite loops crash unity. I think coroutines do something but I don't understand them. Could you help me find how to fix my script and explain how the Wait part of the script works ;-;
using UnityEngine;
using System.Collections;
public class CannonScript : MonoBehaviour {
GameObject prefab;
public GameObject Cannon;
public GameObject Bullet;
public float Bullet_Foward_Force;
void Start ()
{
}
void Update ()
{
for (int i = 0; i < 10; i++ )
{
GameObject temporary_Bullet_handler = Instantiate(Bullet, Cannon.transform.position, Cannon.transform.rotation) as GameObject;
Rigidbody Temporary_Rigidbody;
Temporary_Rigidbody = temporary_Bullet_handler.GetComponent();
Temporary_Rigidbody.AddForce(transform.forward * Bullet_Foward_Force);
//I want to have a script wait here
Destroy(temporary_Bullet_handler, 10.0f);
}
}
}
Answer by RobAnthem · Dec 09, 2016 at 07:56 PM
Your update script is going to attempt to do this process at least 30 times a second, it is going to cause a lot of issues off the bat, and your Destruction method should be an "oncollision" even attached to the bullet.
My suggestion is create a timer, or max bullet count, and make the Update script only instantiate x # of bullets at any given time. Also you could create a simple timed offset in your Update script by just make an int variable like this.
int counter = 0;
void Update
{
counter ++
if (counter > 30)
{
//do stuff
counter = 0;
}
}