- Home /
While loop freezes unity
I'm trying to create an AI that goes to the player, I have a script that is supposed to move the zombie to the player but the zombie didn't move and when I move to the zombie unity freezes, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deformed : MonoBehaviour {
Rigidbody2D rb2D;
Rigidbody2D playerRb2D;
Transform trans;
Transform playerTrans;
public float Distancebetween;
public GameObject player;
void Start () {
rb2D = gameObject.GetComponent<Rigidbody2D> ();
trans = gameObject.GetComponent<Transform> ();
playerTrans = player.GetComponent<Transform> ();
playerRb2D = player.GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
Distancebetween = playerTrans.position.x - trans.position.x;
while (Distancebetween > 0) {
rb2D.AddForce (Vector2.right * playerRb2D.velocity.x);
}
}
}
You can't use while there. You are not modifying Distancebetween inside the loop, once you are inside the while, you'll never exit. Anyway AddForce don't modify immediately the object position. Try with "if" ins$$anonymous$$d "while" and you can check how AddForce works. You'll see a very fast zombie.
Answer by dragonking300 · Jul 17, 2017 at 04:23 PM
Try changing the while loop to a if loop like
if(Distancebetween > 0) {
rb2D.AddForce (Vector2.right * playerRb2D.velocity.x)
}
else
{
//code
}
}
}
Because unity will crash if the loop is infinite
Answer by Dorscherl · Jul 17, 2017 at 05:11 PM
I'm still new to Unity but I know that Update is a loop of it's own. It is called every frame. My theory is that your while loop prevents Unity from going to the next iteration (frame). Not only that, your while loop is an infinite loop and in ANY types of programming that is an error. Your loop control variable isn't being modified in the loop.
I would use an If statement
if (Distancebetween > 0)
{
rb2D.Addforce( Vector2.right * playerRb2D.velocity.x);
}
This way your script won't hinder itself.
Answer by Sneakyshot4012 · Aug 13, 2017 at 01:42 AM
I believe that while loops freezes Unity because the Update() function is basically a while loop of it's own. You will need an if statement to see if the enemy is close to the player, not a while.