Skip to content

Instantly share code, notes, and snippets.

@fallenblood7080
Created January 19, 2022 15:48
Show Gist options
  • Save fallenblood7080/b8f459c475ea3a58d2d8955e8602f6c6 to your computer and use it in GitHub Desktop.
Save fallenblood7080/b8f459c475ea3a58d2d8955e8602f6c6 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class agent : MonoBehaviour
{
private NavMeshAgent navMeshAgent;
List<Transform> patrollingPoints = new List<Transform>();
public Transform patrollPattern;
bool isPatrol;
public float minTimeForNextPatrol;
public float maxTimeForNextPatrol;
float nextTimeToPatrol;
// Start is called before the first frame update
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
for (int i = 0; i < patrollPattern.childCount; i++)
{
patrollingPoints.Add(patrollPattern.transform.GetChild(i));
}
}
// Update is called once per frame
void Update()
{
Patrolling();
}
void Patrolling()
{
int i = Random.Range(0, patrollingPoints.Count);
if (navMeshAgent.remainingDistance < 0.2f && nextTimeToPatrol<=0)
{
isPatrol = false;
}
else
{
isPatrol = true;
}
if (!isPatrol)
{
if (nextTimeToPatrol <= 0)
{
navMeshAgent.SetDestination(patrollingPoints[i].position);
nextTimeToPatrol = Mathf.Round(Random.Range(minTimeForNextPatrol, maxTimeForNextPatrol));
}
else
{
nextTimeToPatrol -= Time.deltaTime;
}
}
else
{
nextTimeToPatrol -= Time.deltaTime;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment