using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Assertions;
[RequireComponent(typeof(NavMeshAgent))]
public class NavMeshTargeting : MonoBehaviour
{
[SerializeField] private NavMeshAgent _targetAgent;
private NavMeshAgent _agent;
private HashSet<NavMeshAgent> _collidedAgents;
private float _cachedSpeed;
private void Awake()
{
_agent = GetComponent<NavMeshAgent>();
Assert.IsNotNull(_targetAgent);
_agent.SetDestination(_targetAgent.gameObject.transform.position);
_collidedAgents = new HashSet<NavMeshAgent>();
_cachedSpeed = _agent.speed;
}
private void Update()
{
if (_collidedAgents.Count > 0)
{
// We're bumping at least one agent, so check if our destination has clear line of sight. if not, stop it
if (Physics.Raycast(transform.position, _agent.destination, out RaycastHit hit, Mathf.Infinity))
{
if (hit.collider.TryGetComponent(out NavMeshAgent blockingAgent))
{
_agent.speed = 0f;
Debug.Log("blocked. freezing motion for " + gameObject.name);
}
else
{
_agent.speed = _cachedSpeed;
Debug.Log("unblocked. Resuming motion for " + gameObject.name);
}
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out NavMeshAgent agent))
{
// we collided with an agent, add it to the list
_collidedAgents.Add(agent);
}
}
private void OnTriggerExit(Collider other)
{
if (other.TryGetComponent(out NavMeshAgent agent))
{
// we're no longer colliding with an agent so remove it
_collidedAgents.Remove(agent);
if (_collidedAgents.Count == 0)
{
_agent.speed = _cachedSpeed;
Debug.Log("unblocked. Resuming motion for " + gameObject.name);
}
}
}
}