- Home /
How do I add a chase player if seen for 10 seconds if not in sight while still returning to navmesh patrol route if player is not seen
I am trying to create a script so that in the maze the enemy will go To different points but will chase the player when the enemy can see the player I do not know if I need a camera or not but I know that After 10 seconds of not seeing the player after just seeing him for example the player turns a corner the ai should chase the player for 10 seconds if not seen again within that time return to patrol pattern but I do not know how to make this work any help would be appreciated please help.
p.s just a beginner.
oh yeah here is the script it would be beneficial if you left a copy with the changes in the script in it I am bad with implementing code just from description's thanks.
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
public class Patrol : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
public GameObject Player;
void Start () {
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint() {
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}
Answer by Warcraft897 · Sep 26, 2019 at 02:34 PM
@derpypickachu01 thanks I will try to make it work though it is not working now I will see what I can do thanks I will update you today later on what happened thank you
No problem! If you wish, you can tell me what issues you've run in and if you're still experiencing them. I'd be happy to help on your call!
the enemy is not moving at all for some reason I hit play and he just stands still
ok so If I move the enemy transform while in play he moves but when the ray hits the player the ai does not care for some reason
Answer by supa4plex2 · Sep 26, 2019 at 05:42 AM
I had some difficulty trying to understand what you were getting at here, but I believe I've come up with a solution to what you're asking to do here. I've added and changed a lot of things to fit the function, and I do admit that it may be a bit messy and rushed.
List of changes:
Casted a Ray in front of the enemy (this should be visible in the Scene view if Gizmos are turned on) and the ray has a adjustable range to it, meaning it can see for as far as you want it to. The colour of the ray is drawn to be cyan as well.
Made a boolean variable which turns true if it's chasing the Player, and false if it's not. If it's true, it will ignore its normal patrolling procedure and only focus on chasing the player.
Added a timer of 10 seconds. The timer will countdown if it's chasing the player as soon as the player is out of the enemy's vision. Once the timer hits 0, the enemy will stop chasing the player and resume to its normal patrol.
If the enemy is chasing the player it will attempt to go inside of it. Of course, this wouldn't be a problem as the colliders would prevent them both from going inside each other, but this function can be useful to use a OnCollisionEnter() method which would do something as soon as the both of them collide.
Note: I have NOT worked in 3D Environments and I have NOT tested this code out yet. I've worked on my own things in different environments. However, this doesn't completely mean that this code will not work right off the bat, although there is a possibility it might. I've implemented what I already know and what I've learnt in the time I researched to tackle this problem, so I have some confidence in this.
I'm aware that not testing this is deemed as sloppy, but instead I just imagined an environment similar to what you described and imagined scenarios where each line of code I wrote would work in the scene.
I noticed you have a Transform Array for the transforms of the wall gameobjects, I think it may be useful to add all the children wall gameobjects, if you have a parent for them, in script using a for loop.
Needless to say, this script may or may not create errors but it's a basic idea of what's supposed to happen. If you do find any errors, I believe that you can figure it out or get a better answer than this. Wish you the best of luck on your project!
The Changed Script
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
using System.Collections.Generic;
public class Patrol : MonoBehaviour
{
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
public float rayDistance = 5f;
private float timeToChase;
private bool isChasingPlayer;
public LayerMask whatToDetect;
public Transform playerTransform;
void Start()
{
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
timeToChase = 10f;
isChasingPlayer = false;
if (playerTransform == null)
Debug.Log("Error. Can't find Player Transform.");
else
playerTransform = GameObject.Find("Player").transform;
CheckAndChase();
}
void CheckAndChase()
{
// Returns if no points have been set up
if (points.Length == 0)
return;
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, transform.forward, out hitInfo, rayDistance, whatToDetect))
{
if (hitInfo.collider != null)
{
// If the ray detects a collider of a GameObject with the tag "Player"
if (hitInfo.collider.CompareTag("Player"))
{
isChasingPlayer = true;
// Each time it detects the Player, the timer is reset to 10 seconds. As soon as the Player is out of the
// Enemy's range, the timer begins to count down.
timeToChase = 10f;
}
// If the Player isn't being detected anymore, the enemy will still change the Player.
else if (isChasingPlayer == true)
{
if (timeToChase > 0)
{
agent.destination = playerTransform.position;
timeToChase -= Time.deltaTime;
}
else
isChasingPlayer = false;
}
else
{
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
}
}
}
void OnDrawGizmosSelected()
{
Debug.DrawLine(transform.position, transform.forward * rayDistance, Color.cyan);
}
void Update()
{
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && ((agent.remainingDistance < 0.5f && isChasingPlayer == false) || isChasingPlayer == true))
CheckAndChase();
}
}
I forgot to add this important step:
For the whatToDetect Layer$$anonymous$$ask, you need to assign the layers in which the enemy is situated in and the other layer in which the walls are situated in. You can achieve this in the Inspector as I've made that Layer$$anonymous$$ask public.
Your answer

Follow this Question
Related Questions
Can you use NavMesh agents to vary driving/handling model? 0 Answers
NavMesh Agent Obstacle Avoidance Ignore 1 Answer
How to add variables to Components (Nav Mesh Agent)? 0 Answers
Modify NavMeshPath for Tactical FPS (slicing the pie/sweeping maneuver) 0 Answers
Navmesh baking -- Odd results 1 Answer