Unity is freezing when I change my script, what can I do? [SOLVED]
Hey guys! I'm currently working on a project in Unity for my classes and I've stumbled on a problem that I don't know how to fix.
I have a script for a character (Unity 2D) that makes it shoot a bullet to kill enemies. At first, when I tested the script, everything was working perfectly fine, however, I had animations to add to the character shooting the bullet, so I needed to relate the character's Animator with the script.
I did that, and the script didn't return any errors, but when I got to playtest it, Unity just froze. I didn't return any errors or warnings, it didn't play, I couldn't close it, so I had to stop its activity via the Task Manager.
public class Shooter : MonoBehaviour
{
public float dirx;
public KeyCode shoot;
public GameObject bullet;
public Animator animatortwo;
void Start()
{
StartCoroutine(waitthree());
}
IEnumerator waitthree()
{
while (true)
{
dirx = Input.GetAxisRaw("Horizontal");
if (dirx == 0)
{
dirx = 1;
}
if (Input.GetKeyDown(shoot))
{
animatortwo.SetTrigger("Shoot");
var newbullet = Instantiate(bullet,
transform.position, transform.rotation);
newbullet.GetComponent<Bullet>().dirx = dirx;
yield return new WaitForSeconds(0.11f);
animatortwo.ResetTrigger("Shoot");
}
}
}
}
Any ideas on why this possibly happened and how can I fix it? When the script was without the Animator, it worked fine.
Answer by joshuapeacock · Jan 09, 2020 at 05:18 PM
You need to yield outside of your if condition. Currently, if you don't have a key down, you have created an infinite loop.
A simple fix would be to yield return null; after your if condition.