Unity crashes when enemy is supposed to follow the player

im trying to create a simple 2d top-down game for practice, and everything that i’ve done up until now with the enemy has worked, but for some reason, whenever the player enters the circle trigger made to check if the enemy should follow the player, unity crashes. Im sure that there is something faulty with the movement script, as when i remove it, the game runs normally.

I dont know if this information helps, but when i accidentally put the “while (followPlayer == true)” loop as an “if”, the enemy did move and the engine ran normally, but of course, because the code isnt in the while loop, the enemy’s movement dosent really do much.

Could someone tell me if there is a problem in the code, or if its something with my engine that needs fixing? Thanks in advance!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoleEnemy : MonoBehaviour
{
	public Rigidbody2D rb;
    public PlayerHealth playerHealth;
	public PlayerController player;

	public float speed = 3f;

	public bool followPlayer = false;

	private void Start()
	{
		rb = this.GetComponent<Rigidbody2D>();
	}
	private void OnCollisionEnter2D(Collision2D collision)
	{
		if(collision.gameObject.tag == "Player")
		{
            playerHealth.TakeDamage();

			player.Knockback(this.gameObject);
			
		}
		
	}

	private void Update()
	{
		while (followPlayer == true)
		{
			Vector2 tempVector2 = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);

			transform.position = new Vector3(tempVector2.x, tempVector2.y, transform.position.z);
		}
	}

	private void FixedUpdate()
	{
	
	}

	private void OnTriggerEnter2D(Collider2D collision)
	{
		if(collision.gameObject.tag == "Player")
		{
			followPlayer = true;
			
		}
	}

	private void OnTriggerExit2D(Collider2D collision)
	{
		if (collision.gameObject.tag == "Player")
		{
			followPlayer = false;
		}
	}
}

(this is all of the code that the enemy has so far)

The reason it crashes is that you have an infinite while loop. All you do is check if the variable followPlayer is true but never change the followPlayer variable. The way Unity’s update loop works is that it finishes all code in the update function, and then it goes on to generate the next frame. This is a simplified explanation. Because your while loop never stops, it will never move on to the next frame. Unity draws to the screen at the end of each frame. So, because the frame never ended, it will never draw the enemy on the way to the player. Unity also takes inputs between frames (simplified), and since the frame never ended, it freezes.

I hear you asking, “What the heck am I supposed to do then?” Well, here is the funny bit: the if-statement solution you provided SHOULD WORK! The way that logic works is that Unity checks each frame if the variable is true, and if it is, it will move the enemy just a bit closer to the player. And because this is being done each frame, and you presumably have at least 60 frames, the little bit that it moves the player closer looks like smooth movement to your human eyes. A tiger might see it as choppy because they have better eyes; fun fact.

Basically, the whole idea is the same as with a flipbook animation, like this one:
(Simple Animation - Dancing Flip Book - YouTube)

Each paper has a frame, and when the papers move fast, it looks like a smooth animation. The idea with Unity’s Update Function (“Loop”) is the same. Each frame has a small movement closer to the player, and together, it looks like smooth movement.

Here is a fast video to show you exactly how your code should look and work. Also, the video shows you a neat trick on how you can make your code look a bit better by putting your two lines for moving the enemy into one line:
(https://www.youtube.com/watch?v=9eTZqxxgGz8)

So the question is, why didn’t your approach with the if statement work?

I don’t know, lol.

My guess is that either:
A) Something else outside of the script influences the enemy or the enemy’s script. So, if something might disable the script or something might set the movement variable to false or something?
B) You’re sure your speed variable isn’t just set too low or maybe even to 0 in the inspector?

Also, I recommend this video that explains the update function:
(C# Update And Fixed Update in Unity! - Beginner Scripting Tutorial - YouTube)

And by the off chance that you’re not familiar with what Time.deltaTime does, here is a short video for that too:
(#11 | TIME.DELTATIME EXPLAINED 🎮 | Unity For Beginners | Unity Tutorial - YouTube)

I would really recommend this one because it explains the update loop and all the details as well.

I hope you find your problem, and get back to me if you need anything else by replying to this comment or something, I don’t know.

By the way, if you haven’t already, I recommend asking ChatGPT first since I tried pasting your question in, and it knew how to fix the code somewhat. But that’s just it; I think something else is wrong because the if-approach should work. Here is my chat with ChatGPT-3.5 (default):
Chat Gpt 3.5 conversation link

And if you’re curious, here is what ChatGPT-4 (premium, paid) says:
Chat Gpt 4 conversation link

When talking to ChatGPT about Unity or any form of code development, I highly advise you not to give up on the first attempt. Talk to it like you would to a human: “Man, ChatGPT, this code doesn’t work, but I know it should; what else could be wrong?” and eventually, you might get somewhere. Best of luck, and don’t forget to update me on what happened :v:.