- Home /
Question by
CycloneWhale · Apr 30, 2020 at 05:36 PM ·
while-loop
While loop crashes unity
Whenever my change direction function is called unity crashes. I'm pretty sure it has to do with the while loop but I don't know why. I'm trying to make the enemy follows the player, but right now whenever the player changes direction the enemy changes direction instantly. I want to make it so that the enemy gradually changes direction.
public class EnemyAI : MonoBehaviour
{
private Animator anim;
private LimbController limbs;
private GameObject player;
public float speed;
private int playerDir;
private int lastPlayerDir;
private float dir;
private void Awake()
{
limbs = GetComponent<LimbController>();
player = GameObject.FindGameObjectWithTag("Player");
anim = GetComponent<Animator>();
}
private void Start()
{
playerDir = player.transform.position.x > transform.position.x ? 1 : -1;
lastPlayerDir = playerDir;
dir = playerDir;
}
private void Update()
{
playerDir = player.transform.position.x > transform.position.x ? 1 : -1;
if(lastPlayerDir != playerDir)
{
ChangeDirection(playerDir);
}
if(player.transform.position.x - transform.position.x > 5 || player.transform.position.x - transform.position.x < -5)
{
limbs.body.bone.velocity = new Vector2(dir * speed, limbs.body.bone.velocity.y);
anim.SetBool("isWalking", true);
}
else
anim.SetBool("isWalking", false);
}
private void ChangeDirection(int changeDir)
{
while(dir != playerDir)
{
dir += changeDir * Time.deltaTime;
}
lastPlayerDir = playerDir;
}
}
Comment
Answer by yogummben · Apr 30, 2020 at 05:41 PM
If your while loop is endless then unity will crush. Happened to me before. You should check is there a way to end your while loop.
Your answer
![](https://koobas.hobune.stream/wayback/20220612232926im_/https://answers.unity.com/themes/thub/images/avi.jpg)