- Home /
Question by
ajrocks404 · Jun 12, 2021 at 04:08 AM ·
instantiatecrashcoroutine
Code freezes Unity and I don't know how to fix
I was making a very basic gun script, I don't remember what I did to make it not work, heres the main code
Animator m_Animator;
public Rigidbody Bullet;
public Transform barrelEnd;
public float firerate = 0.5f;
// Start is called before the first frame update
void Start()
{
m_Animator = gameObject.GetComponent<Animator>();
StartCoroutine(SpawnLoop());
}
IEnumerator SpawnLoop()
{
while (enabled)
{
if (Input.GetButton("Fire1"))
{
Rigidbody rocketInstance;
rocketInstance = Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
m_Animator.SetBool("shoot", true);
yield return new WaitForSeconds(firerate);
}
}
}
void FixedUpdate()
{
m_Animator.SetBool("shoot", false);
}
Sorry for the headaches.
Comment
The specific reason for the infinite loop can be seen when you grab only the important elements:
while (enabled)
{
if (Input.GetButton("Fire1"))
{
yield return new WaitForSeconds(firerate);
}
}
In short, you only yield while the "Fire1" button is held. If you're not, you're stuck in an inescapable loop instead (which holding the button won't alleviate).
Best Answer
Answer by theawesome1 · Jun 12, 2021 at 05:23 AM
try this:
Animator m_Animator;
public Rigidbody Bullet;
public Transform barrelEnd;
public float firerate = 0.5f;
private bool shoot;
// Start is called before the first frame update
void Start()
{
m_Animator = gameObject.GetComponent<Animator>();
StartCoroutine(SpawnLoop());
}
private void Update()
{
if (Input.GetButton("Fire1") && shoot == true)
{
StartCoroutine(SpawnLoop());
}
}
IEnumerator SpawnLoop()
{
shoot = false;
Rigidbody rocketInstance;
rocketInstance = Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
m_Animator.SetBool("shoot", true);
yield return new WaitForSeconds(firerate);
shoot = true;
}
void FixedUpdate()
{
m_Animator.SetBool("shoot", false);
}