Dear coders
I have coded for waypoints to randomly be instantiated and indexed in a list.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.AI;
public class WaypointList : MonoBehaviour {
public GameObject _gameObject;
public List<GameObject> _list = new List<GameObject>();
public float timer;
float x;
float y;
float z;
void Start (){
}
void Update ()
{
List<GameObject> _list = new List<GameObject>();
timer += Time.deltaTime;
if (timer > 1.0f) {
WaypointGenerate();
timer = 0f;
}
x = Random.Range(-500, 500);
y = Random.Range (1, 5);
z = Random.Range(-500, 500);
}
void WaypointGenerate ()
{
GameObject clone = Instantiate (_gameObject) as GameObject;
clone.transform.position = new Vector3 (x,y,z);
_list.Add (_gameObject);
}
}
My enemy is able to access this list and on a timer randomly pick one of the indexed waypoints.
System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.AI;
public class RandomEnemyWander : MonoBehaviour {
public float timer;
private NavMeshAgent patrol;
public List<GameObject> points;
public GameObject wayPointManagerObject;
[HideInInspector] WaypointList wplist;
public int index;
GameObject currentPoint;
[HideInInspector] GameObject wpClone;
void Start ()
{
patrol = GetComponent<NavMeshAgent> ();
wplist = wayPointManagerObject.GetComponent<WaypointList> ();
points = wplist._list;
}
void Update (){
timer += Time.deltaTime;
if (timer > 10.0f) {
pickWayPoint ();
timer = 0f;
}
}
public void pickWayPoint (){
index = Random.Range (0, points.Count);
currentPoint = points [index];
patrol.destination = currentPoint.transform.position;
Debug.Log (currentPoint.name);
}
}
However, regardless of the indexed waypoint picked, the enemy only ever moves toward the ‘first’ and original waypoint gameobject and stays there regardless of whatever indexed waypoint is picked.
Would someone be able to give a suggestion as to how I can get the enemy to move toward the waypoint in Index?
Thanks!