I’m currently writing a script for an AI character that is supposed to follow a path drawn by the user. The user traces a path by moving a cube GameObject. My method involves hitting a key at a certain location to make that location part of the path. This location is put into an array of Vector3s. After all the points are set, the user initiates the path follow function and the character moves to each “way point”.
My question is pretty simple, but I’ve only ever used C++ so I’m not sure how to do it. The way I’m trying to set the points and add them to the array is this:
function setDynamicPath(){
var i = 0;
if (Input.GetKey("p")){
var newLocation : Vector3 = cube.transform.position;
newLocation = pathPoints[i];
i++;
//newLocation.delete; //how do I delete a variable?
}
}
Basically I want to create a temp variable at the current position of the cube gameobject (newLocation), put it into the array (pathPoints) at item i, and delete that temp variable. Is there an easy way to accomplish this in Unity?
Once that’s done I just want to have the character move between each point in the array.
Hmm. Still having issues. I’ll spend more time looking into the garbage collection here later, a little pressed for time at the moment. Mainly with populating the array. When calling the function in Update, I checked the size of the array after trying to add 10 or so points, it returns 0. Anyone have a fix?
var pathPoints : Vector3[]; //array of points for the path to follow
var newLocation : Vector3; //new location to put in array
function dynamicPath(pos : Vector3){
for (var i = 0; i < pathPoints.Length; i++){
var tempTarget = pathPoints[i]; //next point to move to
//rotate towards and move to the target
var targetRotation = Quaternion.LookRotation(pos - this.transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime*2);
transform.position = Vector3.MoveTowards(this.transform.position, tempTarget.position, Time.deltaTime*speed);
}
}
//user can move cube to draw a path on screen, character follows that path
function drawDynamicPath(){
var i = 0;
if (Input.GetKey("p")){
newLocation = cube.transform.position;
newLocation = pathPoints[i];
i++;
}
}
As JRavey said, your assignment is backwards. In drawDynamicPath, you are doing this:
newLocation = pathPoints*;* when you should be doing this: pathPoints = newLocation; However, you’d also need to move that “i” out of the method itself and make it a class member at the top of your class, and set it to zero there. Otherwise, you’re setting it back to 0 every time you call drawDynamicPath. But a better idea, to make your life easier, is to make pathPoints an ArrayList instead of an array. Then you can just say pathPoints.Add(newLocation) to add it to the end, and not have to track how many elements are in the array or where you’re currently pointing.