- Home /
NavMeshAgent Finding Alternative Route
I am working on a project where the AI can react to the player.
I have a simple AI built for the Alien Enemy
using UnityEngine;
using System.Collections;
using System;
public class basic_alien_ai : MonoBehaviour {
private NavMeshAgent alien_nav;
public Transform point;
public float hit_points = 20;
private bool attacking_enemy;
private GameObject current_target;
public LayerMask alien_layer;
void Awake()
{
alien_nav = GetComponent<NavMeshAgent>();
current_target = point.gameObject;
}
void Update()
{
print(attacking_enemy);
if (hit_points <= 0)
{
Destroy(gameObject);
}
try
{
alien_nav.SetDestination(current_target.transform.position);
}catch(Exception e)
{
print("error");
}
if (current_target.Equals(null) || current_target == null)
{
attacking_enemy = false;
current_target = point.gameObject;
}
if (attacking_enemy == false)
{
transform.LookAt(current_target.transform.position);
}
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 20, ~alien_layer))
{
if (hit.collider.tag == "enemy")
{
attacking_enemy = true;
current_target = hit.collider.gameObject;
}
}
}
void OnCollisionEnter(Collision alien_hit)
{
if(alien_hit.gameObject.tag == "enemy")
{
Destroy(alien_hit.gameObject);
}
}
}
This will make the Alien go to the Destination and also look for any player owned units. If it finds one it will go toward it, then it will continue on.
I wanted to know if there was away so the Alien could find another way to the destination(if there is one)
In other words the NavMeshAgent looks for the next possible way to its destination if there is one. I have yet to come up with anything, or if it is even possible with the NavMesh.
Thank you for any help.
Answer by M-Hanssen · May 11, 2016 at 10:35 AM
Be careful! you are Setting the destination of the enemy EACH frame! You should set it only once, so check if the NavmeshAgent has a path or something before assigning a new destination. Use something like this:
if (!alien_nav.hasPath)
{
alien_nav.SetDestination(current_target.transform.position);
}
I do not understand your question exactly. Are you trying to find a way to make the navmeshAgent find a different path than the default shortest path?
"Are you trying to find a way to make the navmeshAgent find a different path than the default shortest path?"
Yes, how would you accomplish this?