Unity协程实现场景中的鼠标按住物体跟随鼠标移动
void Awake()
{
StartCoroutine(OnMouseDown() as IEnumerator);
}
IEnumerator OnMouseDown(){Vector3 targetScreenPos = Camera.main.WorldToScreenPoint(transform.position);Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenPos.z));while (Input.GetMouseButton(0)){Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenPos.z);Vector3 targetPos = Camera.main.ScreenToWorldPoint(mousePos) + offset;transform.position = targetPos;yield return new WaitForFixedUpdate();}}//协程名必须是OnMouseDown