Playing around coroutines, but got stuck on this one, pretty sure it’s the while loop, but I don’t get it why? ![]()
The point of this script, is just to move an object smoothly using Vector3.Lerp to random locations. ![]()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoroutinePrototype : MonoBehaviour {
// Use this for initialization
void Start () {
Vector3[] coordinateArray = new Vector3[16]; //create an Array
for (int i = 1; i < 16; i++) {
coordinateArray [i] = new Vector3 (RandomCoordinate (), RandomCoordinate (), RandomCoordinate ()); //put vector in each slot of array with random values
}
StartCoroutine(SendCords(coordinateArray, 1f)); //start cooroutine
}
float RandomCoordinate(){ //random value generator
float randomNumber = Random.Range (-50f, 50f);
return randomNumber;
}
void moveTo(Vector3 location) { //function to move object to specified location (parameter)
Debug.Log ("Moving object to location:" + location);
transform.position = Vector3.Lerp(transform.position, (transform.position - location), 0.01f);
Debug.Log ("Arrived");
}
IEnumerator SendCords (Vector3[] coordinates, float delay){ //the premise of this coroutine is to have a "efficient" delay between each move to location
foreach (Vector3 location in coordinates) { //go through the array and pass values to variable location
while (Vector3.Distance(transform.position, location) > 0.05f) { //while the distance between object and location is bigger, run function moveTo
moveTo (location); //move the object
}
yield return new WaitForSeconds (delay); //delay between each move (object moves slowly using lerp, successfully gets to the point, then delay happens and it repeats)
}
}
// Update is called once per frame
void Update () {
}
}