# Unity之"诡异"的协程

```public class CarMove : MonoBehaviour
{
public float Speed = 1f;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * Speed * Time.deltaTime);
}

}```

```public class CurveCollider : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{

}

private void OnCollisionEnter(Collision collision)
{
if (this.CompareTag("TurnLeft"))
{
StartCoroutine(CarTurnLeft(collision));
}
}

IEnumerator CarTurnLeft(Collision collision)
{
while (true)
{
Vector3 worldUp = Vector3.up;
Vector3 targetPos = collision.transform.position;
Vector3 direction = transform.position - targetPos;
Vector3 forwardDir = new Vector3(-1.0f, 1.0f, 1.0f);
Vector3.OrthoNormalize(ref worldUp, ref direction, ref forwardDir);
Quaternion quaternion = Quaternion.identity;
quaternion.SetLookRotation(forwardDir);
collision.transform.rotation = quaternion;
yield return null;
Debug.Log(collision.transform.eulerAngles.y);
if (collision.transform.eulerAngles.y >= 270 && (collision.transform.eulerAngles.y - 270) <= 1)
{
quaternion = Quaternion.identity;
quaternion.eulerAngles = new Vector3(0.0f, -90.0f, 0.0f);
collision.transform.rotation = quaternion;
yield break;
}
}
}
}```

UnityEngine所提供的SDK都只能在单线程中调用，而协程也是单线程的，不同于多线程。

Unity中只代码只要有一个地方代码出现死循环或者运行时间较长，游戏就会卡死。

```private void OnCollisionEnter(Collision collision)
{
if (this.CompareTag(collision.gameObject.tag))
{
GameController.Score++;
}
Destroy(collision.gameObject);
}```

`if (collision.transform.eulerAngles.y >= 270 && (collision.transform.eulerAngles.y - 270) <= 1)　`

原文作者：M-Anonymous
原文地址: https://www.cnblogs.com/M-Anonymous/p/16883465.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。