I would like to have a script that allows the enemy to patroll on a navmesh, but as soon as he “sees” the player, another script gets activated (the chasing script that i have already made). It would be cool if the script had the function that if the player is (for example) 5 meters away, then the chasing script is deactivating (false) again until he sees the player again…
Something like this:
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
public GameObject player;
public Vector3[] patrolPoints; //Add in inspector
private int patrolPoint = 0;
private NavMeshAgent agent;
void Patrol(){
agent.Resume();
if(patrolPoints.Length > 0){
agent.SetDestination(patrolPoints[patrolPoint]);
if(transform.position == patrolPoints[patrolPoint] || Vector3.Distance(transform.position,patrolPoints[patrolPoint])<0.2f){
patrolPoint++; //use distance if needed(lower precision)
}
if(patrolPoint >= patrolPoints.Length){
patrolPoint = 0;
}
}
}
void Attack(){
//??? your job...
agent.Stop(); //maybe not needed
Debug.Log("Whaaaaaaa"); //just to get informed
}
void Start() {
agent = GetComponent<NavMeshAgent>();
}
void Update(){
if(!Physics.Linecast(transform.position,player.transform.position,1)){ //check if we see player by linecasting,move player to another layer so the ray won't hit it.
Attack();
}else {
Patrol();
}
}
}