MoveTowards with StartCoroutine in update
I have a Queue to record the object move path, and I want to move the object according the path ; But the object not move .
void Start () {
GameObject beta_actor = Resources.Load("beta_actor") as GameObject;
character_ins = Instantiate(beta_actor);
character_ins.SetActive(true);
runPath.Enqueue(new Vector3(254, 0, 255));
runPath.Enqueue(new Vector3(253, 0, 255));
runPath.Enqueue(new Vector3(252, 0, 255));
}
void Update () {
StartCoroutine(Move_Coroutine());
}
private IEnumerator Move_Coroutine() {
Debug.Log("Move_Coroutine");
while (runPath.Count > 0) {
Vector3 endPos = runPath.Dequeue();
Move_Trans(character_ins.transform.position, endPos, 5);
yield return null;
}
Debug.Log("Move_Coroutine done");
}
private void Move_Torwards(Vector3 startPos, Vector3 endPos, float moveMax)
{
if(Vector3.Distance(startPos, endPos) <= 0.1f)
{
return;
}
float maxDistanceDelta = Time.deltaTime * moveMax;
character_ins.transform.position = Vector3.MoveTowards(character_ins.transform.position, endPos, maxDistanceDelta);
Debug.Log("Move_Torwards " + character_ins.transform.position + " endPos " + endPos + " " + maxDistanceDelta);
}
Comment
Best Answer
Answer by UnityCoach · Feb 27, 2017 at 08:00 AM
Starting a coroutine from Update will start a new instance of that coroutine every frame.
You can use InvokeRepeating("Move_Coroutine", delay, rate)
instead.
Or simply put that code within the Update call.
Or start the coroutine from Start (), and yield WaitForEndFrame.
Your answer
Follow this Question
Related Questions
Character rolls forward,but slides back after animation 2 Answers
Visual Studio 2015 keeps crashing... 1 Answer
Day/Night cycle turns black at night and how to Serialize it rightly? 0 Answers
MobController 1 Answer
NullReferenceException: Object reference not set to an instance of an object 1 Answer