我正在構建 Unity 3D 游戲,如果用戶處于第三級,我想簽入腳本。如果為 true,則否則 .我嘗試將這個簡單的if語句實現到腳本中,但我得到了:timeLeft = 120;timeLeft = 90;Invalid token 'if' in class, struct, or interface member declaration如果我將語句放入 start 方法中,我得到:The name 'timeLeft' does not exist in the current context如何解決?計時器.cspublic class Timer : MonoBehaviour{ public Collide _collide; Text instruction; private void Start() { instruction = GetComponent<Text>(); InvokeRepeating("time", 0, 1); } if (SceneManager.GetActiveScene().buildIndex == 7) int timeLeft = 120; else int timeLeft = 90; private void time() { int buildIndex = SceneManager.GetActiveScene(); if (_collide.obji <= 0 && timeLeft > 0) SceneManager.LoadScene(buildIndex switch { 1 => 2, 3 => 5, 7 => 9 }); else if (_collide.obji > 0 && timeLeft <= 0) SceneManager.LoadScene(buildIndex switch { 1 => 3, 3 => 6, 7 => 8 }); if (timeLeft > 0) { timeLeft -= 1; instruction.text = (timeLeft).ToString(); } else if (timeLeft <= 0) instruction.text = "0"; }}
2 回答

慕娘9325324
TA貢獻1783條經驗 獲得超4個贊
由于 timeLeft 用于類,因此不能在方法中聲明它。將其向上移動并將代碼放在開頭。
public class Timer : MonoBehaviour
{
int timeLeft;
void Start()
{
instruction = GetComponent<Text>();
InvokeRepeating("time", 0, 1);
if (SceneManager.GetActiveScene().buildIndex == 7)
{
timeLeft = 120;
}
else
{
timeLeft = 90;
}
/*
timeLeft = (SceneManager.GetActiveScene().buildIndex == 7) ? 120 : 90;
*/
}
}
注釋行是相同的,只是寫得不同。
- 2 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消