- Home /
Waypoint Recognition
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!
First thing I would try is to remove the line List _list = new List(); from the Update in your WaypointList script.
Answer by niocy · Dec 23, 2017 at 04:24 PM
The problem is that you are copying the list of waypoints in the start of randomenemywander, so it will never change. Change your code so that pickwaypoint() copies the current waypoints first and then selects the waypoint
@niocy All fixed - typo on my behalf! Thankyou for your help!
Answer by ohkayem · Dec 23, 2017 at 08:29 PM
@niocy Thanks for your answer. I've tried every variation of your answer but to no luck.
Could it be that each time a new waypoint is instantiated it is instantiated as a clone? I only ask because every time I click on an indexed waypoint, it highlights the original waypoint which is the first one that the enemy walks toward.
I hope this makes sense - any more help would be gratefully appreciated!