I am new to Unity and Scripting. So far I have a code to where my AI makes a patrol around my Nav Mesh. I want to have it chase the player and attack the player when the player comes into a certain range, but return to patrolling once the player gets out of that range. This is for an Oculus project. Any help is greatly appreciated. Here is the code I have so far:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NPCSimplePatrol : MonoBehaviour
{
//Dictates whether the agent waits on each node
[SerializeField]
bool _patrolWaiting;
//The total time we wait at each node
[SerializeField]
float _totalWaitTime = 3f;
//The probability of switching direction
[SerializeField]
float _switchProbability = 0.2f;
//The list of all patrol nodes to visit
[SerializeField]
List<Waypoint> _patrolPoints;
//Private variables for base behaviour
NavMeshAgent _navMeshAgent;
int _currentPatrolIndex;
bool _travelling;
bool _waiting;
bool _patrolForward;
float _waitTimer;
public Transform player;
static Animator anim;
//Use this for initialization
public void Start()
{
anim = GetComponent<Animator>();
_navMeshAgent = this.GetComponent<NavMeshAgent>();
if(_navMeshAgent == null)
{
Debug.LogError("The nav mesh agent component is not attached to " + gameObject.name);
}
else
{
if(_patrolPoints != null && _patrolPoints.Count >= 2)
{
_currentPatrolIndex = 0;
SetDestination();
}
else
{
Debug.Log("Insufficient patrol points for basic patrolling behaviour.");
}
}
}
public void Update()
{
//Check if we're close to destination
if (_travelling && _navMeshAgent.remainingDistance <= 1.0f)
{
_travelling = false;
//If we're going to wait, then wait
if (_patrolWaiting)
{
_waiting = true;
_waitTimer = 0f;
}
else
{
ChangePatrolPoint();
SetDestination();
}
}
//Instead if we're waiting
if (_waiting)
{
anim.SetBool("IsIdle", true);
anim.SetBool("IsWalking", false);
anim.SetBool("IsAttacking", false);
_waitTimer += Time.deltaTime;
if (_waitTimer >= _totalWaitTime)
{
_waiting = false;
ChangePatrolPoint();
SetDestination();
anim.SetBool("IsIdle", false);
anim.SetBool("IsWalking", true);
anim.SetBool("IsAttacking", false);
}
}
}
private void SetDestination()
{
if (_patrolPoints != null)
{
Vector3 targetVector = _patrolPoints[_currentPatrolIndex].transform.position;
_navMeshAgent.SetDestination(targetVector);
_travelling = true;
}
}
/// <summary>
/// Selects a new patrol point in the available list but
/// also with a small probability allows for us to move forward or backwards
/// </summary>
private void ChangePatrolPoint()
{
if(UnityEngine.Random.Range(0f, 1f) <= _switchProbability)
{
_patrolForward = !_patrolForward;
}
if (_patrolForward)
{
_currentPatrolIndex = (_currentPatrolIndex + 1) % _patrolPoints.Count;
}
else
{
if(--_currentPatrolIndex < 0)
{
_currentPatrolIndex = _patrolPoints.Count - 1;
}
}
}
}