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();
}