Several NPC with waypoints
Hello! I am making several NPC (enemies) with states and waypoint system in different parts of the terrain. Right now, I did one npc, but I stack with choosing how to make several - will it be better to create for each NPC specific waypoints with specific tags (like firstWaypoints, secondWaypoints) or there are some way to make it better? Code for waypoints:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class GameEnvironment : MonoBehaviour
{
// Private list for storing waypoints for enemy
private List<GameObject> firstWaypoints = new List<GameObject>();
// Usage of getter to return a list of waypoints
public List<GameObject> Waypoints { get { return firstWaypoints; } }
// Singleton pattern
public static GameEnvironment Instance { set; get; }
private void Awake()
{
if(Instance == null)
{
// Reference to the object itself
Instance = this;
DontDestroyOnLoad(this.gameObject);
// Search all waypoints with tag
Instance.Waypoints.AddRange(GameObject.FindGameObjectsWithTag("FirstWaypoint"));
// Sort them to have a correct path
Instance.firstWaypoints = Instance.firstWaypoints.OrderBy(firstWaypoint => firstWaypoint.name).ToList();
//Debug.Log("number of waypoints:" + Instance.waypoints.Count);
} else
{
Destroy(this.gameObject);
}
Debug.Log("Waypoints:" + Waypoints[1]+","+ Waypoints[2]+","+ Waypoints[3]);
Debug.Log("Waypoint:" + firstWaypoints[1]+","+ firstWaypoints[2]+","+ firstWaypoints[3]);
}
}
And state "Patrol": public override void Update() { // Distance before waypoint if (agent.remainingDistance < 1) { if (currentIndex >= GameEnvironment.Instance.Waypoints.Count - 1) currentIndex = 0; else currentIndex++;
agent.SetDestination(GameEnvironment.Instance.Waypoints[currentIndex].transform.position);
}
if(CanSeePlayer())
{
Debug.Log("Player is visible, pursue");
nextState = new Pursue(npc, agent, anim, player);
stage = EVENT.EXIT;
}
//base.Update();
}
Answer by TjazS · Dec 10, 2020 at 07:48 PM
Check out this video https://www.youtube.com/watch?v=TJCOC0gcU4k. I used it in one of my games but I couldn`t find it. All you need to do is insted of Vector move forward use NavMeshAgent.SetDestination(current.position). Hopefully it helps.
USSLES STUF: But the thing is that loops so if you want to go with just one run you will need to find it yourself, beacuse i don`t know how to do it beacuse im developing game just for 5 months now :D.