I’m making a horror game but I have a problem with the AI, It doesn’t work! When The Player is near it start glitching but when it’s at spawn it starts shaking. Any Help? Here’s 3 screenshot’s:
Edit: Here’s my code (I Changed a little bit)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour
{
Transform playerTransform;
UnityEngine.AI.NavMeshAgent myNavmesh;
public float checkRate = 0.01f;
float nextCheck;
// Start is called before the first frame update
void Start()
{
if(GameObject.FindGameObjectWithTag(“Player”).activeInHierarchy)
playerTransform = GameObject.FindGameObjectWithTag(“Player”).transform;
Check rate is much to high use 1s here or even higher. Your if statement was wrong …
You can call CancelInvoke() if the agent should stop hunting.
Here’s some working code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
Transform player;
NavMeshAgent agent;
public float checkRate = 1f;
float nextCheck;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
agent = gameObject.GetComponent<NavMeshAgent>();
agent.updateRotation = true; // rotate the agent always to the player
agent.stoppingDistance = agent.radius * 2f; // we do this so the agent dont move the player away
InvokeRepeating("FollowPlayer", checkRate, checkRate); // follows the player again every checkRate seconds
}
void FollowPlayer()
{
agent.SetDestination(player.position); // should do the job if your navmesh is setup correctly
}
}
There’s an error now saying
“SetDestination” can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)
EnemyAI:FollowPlayer() (at Assets/EnemyAI.cs:34)
EnemyAI:Update() (at Assets/EnemyAI.cs:27)