1.比较协程和Update,LateUpdate
public class Corutine : MonoBehaviour
{
//协程实现分帧执行,提高运行效率
void Start()
{
print("Starting" + Time.time + " seconds");
StartCoroutine(WaitAndPrint());
print("Coroutine started");
}
private void Update()
{
print("Update" + Time.time + " sceconds");
}
private void LateUpdate()
{
print("LateUpdate" + Time.time + " sceconds");
}
private IEnumerator WaitAndPrint()
{
print("尚未挂起!");
yield return null;
//yield return 0/null 表示接下来的语句在下一帧执行,这帧不执行,为挂起状态
print("Coroutine ended" + Time.time + " seconds");
}
//协程在Update和LateUpdate之间运行,协程和主程并行运行,和线程类似
}
2. 通过Lerp使物体移动
下面脚本绑定在方块上,设置一个空物体命名为target
public class CoroutineExample : MonoBehaviour
{
public float smoothing = 1f;
public Transform target;
void Start()
{
StartCoroutine(Mycoroutine(target ));
}
private IEnumerator Mycoroutine (Transform target)
{
while (Vector3 .Distance (transform .position ,target .position) > 0.05f)
{
//距离大于0.05f时,一帧执行一次,跳出来,判断一次,等下一帧继续运行while判断
transform.position = Vector3.Lerp(transform.position, target.position, smoothing * Time.deltaTime);
yield return null;
}
print("Reached the target");
yield return new WaitForSeconds(3f);//三秒后执行下面完成语句
print("Mycoroutine is now finished");
}
}
点击运行方块会移动至目标点。
3.点击圆球使方块向圆球移动
方块上的脚本:
public class PropretiesAndCoroutine : MonoBehaviour
{
public float smoothing = 7f;
private Vector3 target;
public Vector3 Target
{
get { return target; }
set
{
target = value;
StopCoroutine("Movement");
StartCoroutine("Movement", target);
}
}
IEnumerator Movement(Vector3 target)
{
while (Vector3 .Distance (transform .position ,target) > 0.05f)
{
transform.position = Vector3.Lerp(transform.position, target, smoothing * Time.deltaTime);
yield return null;
}
}
}
圆球上的脚本:
public class ClikSetPosition : MonoBehaviour
{
public PropretiesAndCoroutine coroutineScript;
private void OnMouseDown()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit);
Vector3 newTarget = hit.point;
coroutineScript.Target = newTarget;
}
}