[英]Unity punch coroutine not finishing
所以我有如下代碼。
void Update() {
// WASD Movement
if (Input.GetKey(KeyCode.W)) { movementUpdate.y += movementPerSecond * Time.deltaTime; }
if (Input.GetKey(KeyCode.A)) { movementUpdate.x -= movementPerSecond * Time.deltaTime; }
if (Input.GetKey(KeyCode.S)) { movementUpdate.y -= movementPerSecond * Time.deltaTime; }
if (Input.GetKey(KeyCode.D)) { movementUpdate.x += movementPerSecond * Time.deltaTime; }
playerBody.position = playerBody.position + movementUpdate;
movementUpdate = new Vector3(0, 0, 0);
// Body rotation relative to cursor position
Vector3 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
playerBody.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
// hand position via function
UpdateHandPosition(playerLeftHand, desiredPositionForLeftHand);
UpdateHandPosition(playerRightHand, desiredPositionForRightHand);
if (Input.GetMouseButtonDown(0)) {
Punch();
}
}
...
void Punch() {
StartCoroutine(PunchCoroutine());
}
IEnumerator PunchCoroutine() {
Debug.Log("User punched.");
if (onLeftHandPunch = false) {
print(onLeftHandPunch);
onLeftHandPunch = false;
// punch the shit
desiredPositionForLeftHand = "middleMiddleCoordinates";
yield return new WaitForSeconds(1f);
Debug.Log("Corountine finished.");
desiredPositionForLeftHand = "topMiddleCoordinates";
} else {
print(onLeftHandPunch);
onLeftHandPunch = true;
// punch the shit
desiredPositionForRightHand = "middleMiddleCoordinates";
}
}
但是,當我播放代碼並單擊鼠標左鍵時,控制台中將顯示以下內容。
User punched.
False
協程將無法完成並顯示
Coroutine finished.
有人可以幫我嗎? 我認為問題出在WaitForSeconds區域,但我不知道。 我看過其他代碼示例,它應該可以正常工作。 希望你們有一些答案。
另一個答案是正確的,因為問題是if (onLeftHandPunch = false)
行,但是關於原因為什么邏輯不正確...
您的原始代碼:
if (onLeftHandPunch = false) {
} else {
}
將始終運行else
部分,因為它將onLeftHandPunch
設置為false
,然后評估if語句。 結果為if (false)
,這意味着將運行else
。
修復很簡單,使用==
比較運算符而不是=
賦值運算符:
if (onLeftHandPunch == false) {
} else {
}
您的協程已完成,但僅在第一個“ if”語句中打印“協程已完成”,而不在“ else”中打印。 如果將其移至if
語句的底部,您將看到協程確實在“完成”,但未運行所需的邏輯。
在if語句中, if (onLeftHandPunch = false)
,則實際上是將變量設置為false。 您應該使用'=='運算符。 實際上,這將始終為true,因為它始終可以將變量設置為false。 另外,您可能想將WaitForSeconds(1f)更改為WaitForSeconds(1.0f),Unity會對此稍好一些。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.