Movement Script

Hello there,

Someone please explain this, i saw this code from unity answers. I want to to what is the use of this code. its working perfect, but i need to know how to use this…

using UnityEngine;

using System.Collections;

public class AIMove : MonoBehaviour


public Vector3 Position_Two;

IEnumerator Start()

	Vector3 Position_One = transform.position;
		yield return StartCoroutine (MoveObject(transform, Position_One, Position_Two, 3.0f));
		yield return StartCoroutine (MoveObject(transform, Position_Two, Position_One, 3.0f));

IEnumerator MoveObject (Transform thisTransform, Vector3 startPos, Vector3 endPos, float time) 
	float i = 0.0f;
	float rate = 1.0f / time;
	while (i < 1.0f) 
		i += Time.deltaTime * rate;
		thisTransform.position = Vector3.Lerp(startPos, endPos, i);
		yield return null; 



Everything is happening because of the coroutines.

Start gets called just after the game object is instantiated. Then it yields a coroutine. When you yield a coroutine, the code waits for it to end before it goes to the next line. When does a coroutine end? When it has reached the last line of its code. However a coroutine could yield a time (say 1 second), so the coroutine would get paused 1 second before being finished.

Yielding null is a special case. It will make the coroutine stop until the next frame, which is exactly the same that waiting for Time.deltaTime seconds.

Therefore, the MoveObject coroutine increases i in a loop until the condition is true. Then it doesn’t yield anything so it simply ends. At that point your gameObject is at position 2. Then the process starts again only that this time you perp from position 2 to the origin.

Summarizing: in this script you set only the destination position, and your character/object/whatever will go there and back to its original position in 6 seconds until the end of ages.

Edit: check here for further detail.