Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using UnityEngine;
- using UnityEngine.AI;
- namespace Platinio.AI
- {
- /// <summary>
- /// Generate the path and let us know when we have compute one
- /// </summary>
- [RequireComponent(typeof(NavMeshAgent))]
- public class PathGenerator : MonoBehaviour
- {
- [SerializeField] private float m_maxProcessingTime = 1.0f;
- private NavMeshAgent m_agent = null;
- private NavMeshObstacle m_obstacle = null;
- private bool m_processing = false;
- private Coroutine m_coroutine = null;
- private float m_timer = 0.0f;
- public bool Processing { get { return m_processing; } }
- private void Awake()
- {
- m_agent = GetComponent<NavMeshAgent>();
- m_obstacle = GetComponent<NavMeshObstacle>();
- }
- /// <summary>
- /// Calculate a new path
- /// </summary>
- /// <param name="position">destination</param>
- /// <param name="onComplete">called when path is complete</param>
- public void CalculatePath(Vector3 position , Action onComplete)
- {
- if(m_coroutine != null)
- StopCoroutine(m_coroutine);
- m_coroutine = StartCoroutine( CalculatePathRoutine(position , onComplete) );
- }
- public void CancelPathGeneration()
- {
- if (m_coroutine != null)
- StopCoroutine(m_coroutine);
- m_processing = false;
- }
- private IEnumerator CalculatePathRoutine(Vector3 position , Action onComplete)
- {
- m_processing = true;
- m_timer = 0.0f;
- //if the obstacle is enable disable it and give a frame so the navmesh can be update and hole can be filled
- if (m_obstacle.enabled)
- {
- m_obstacle.enabled = false;
- yield return new WaitForSeconds(Time.deltaTime);
- }
- //if the agent was disable give him a frame to
- if (!m_agent.enabled)
- {
- m_agent.enabled = true;
- yield return new WaitForSeconds(Time.deltaTime);
- }
- m_agent.SetDestination(position);
- yield return new WaitForSeconds(Time.deltaTime);
- while ((!m_agent.hasPath || m_agent.pathStatus != NavMeshPathStatus.PathComplete || m_agent.desiredVelocity == Vector3.zero || m_agent.pathPending) && m_timer < m_maxProcessingTime)
- {
- if (!m_agent.enabled)
- {
- CancelPathGeneration();
- yield break;
- }
- yield return new WaitForSeconds(Time.deltaTime);
- m_timer += Time.deltaTime;
- }
- //wait a extra frame
- yield return new WaitForSeconds(Time.deltaTime);
- //something goes wrong generating the path generate a new one
- if (m_agent.enabled && ( !m_agent.hasPath || m_agent.desiredVelocity == Vector3.zero))
- {
- //clean the path
- m_agent.path = new NavMeshPath();
- CalculatePath(position , onComplete);
- }
- else if(m_agent.enabled)
- {
- onComplete();
- }
- m_processing = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment