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)