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);

		}
	}
}

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

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.

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.