Unity AI problem
I have made an AI in unity and it works fine when its set too follow the player but when its set to go after a stationary cube called "Door" it stops working. The door is just a ordinary cube if that makes any difference. I have no clue why and was wondering if anyone could help. This is the code for the AI:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour
{
public float lookRadius = 50f;
public Transform target;
NavMeshAgent agent;
// Start is called before the first frame update
void Start()
{
target = GameObject.Find("Player").transform;
Debug.Log(target);
Debug.Log(lookRadius);
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= lookRadius)
{
agent.SetDestination(target.position);
if (distance <= agent.stoppingDistance)
{
// Attack target
FaceTarget();
}
}
}
void FaceTarget()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
}
void OnDrawGizmosSelected ()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
}
Answer by streeetwalker · Jul 04, 2020 at 05:31 AM
Hi @RealSkizze It could be the door position is not at a valid, walkable destination point on your mesh. To verify the result do this:
bool gotDestination = agent.SetDestination(target.position); debug.Log( "gotDestination = " + gotDestination );
Remember that positions are the locations of the objects transforms. Make sure the door's transform.position.y is within the range of the navmesh's parameters.
Alright so put that in my script and its saying that its not finding the destination so I'm going too try and make it go after and empty game object that I can place in front of the door and this did the trick, thanks for the help.
Your answer
Follow this Question
Related Questions
pathfinding Error or follow player 0 Answers
NavMesh Agent blocked path 0 Answers
Unity Navmesh agent patrol and chase player script issues. 0 Answers
How to exclude certain navmesh obstacles on runtime? 2 Answers