Problem with de-bugging

hi, im quite new to unity and please forgive me if i wasted your time, but a piece of code of mine soft locks unity into an eternal state of loading every time i try to run my code, but there isnt any loops in the script that have on end. code attached below, thanks.

using System.Collections;
using System.Collections.Generic;
using Unity.AI.Navigation;
using UnityEngine;
using UnityEngine.AI;

public class EnemyLogic : MonoBehaviour
{
    public GameObject Player;
    NavMeshAgent agent;
    public Transform[] waypoints;
    void Start()
    {
        int childnum = 0;
        agent = gameObject.GetComponent<NavMeshAgent>();
        foreach (Transform child in GameObject.Find("Waypoints").transform)
        {
            childnum++;
        }
        waypoints = new Transform[childnum];
        childnum = 0;
        foreach (Transform child in GameObject.Find("Waypoints").transform)
        {
            waypoints[childnum] = child;
            childnum++;
        }
    }

    // Update is called once per frame
    void Update()
    {
        Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, 25f, layerMask: LayerMask.NameToLayer("Player"));
        if (colliders.Length > 1)
        {
            foreach (Collider collider in colliders)
            {
                agent.destination = Player.transform.position;
            }
        }
        else
        {
            foreach (Transform waypoint in waypoints)
            {
                agent.destination = waypoint.position;
                while (gameObject.transform.position != waypoint.position)
                {
                   
                }
            }
        }
    }
}

Uh, you have a while-loop on line 45 that does nothing. That will just spin on infinitely and Unity will not proceed at all. I imagine this should just be a regular if-statement instead.

4 Likes

Also don’t compare positions, or any float value. Float values may never be precisely identical, this is why Mathf.Approximately exists. But in case of positions you always have to leave greater room by introducing a “close enough” threshold.

Do this instead:

var distance = (gameObject.transform.position - waypoint.position).magnitude;
if (distance < 0.1f) { .. }

The threshold needs to account for the maximum velocity of both objects combined.

Oh, thank you

Thankyou