Unity的C#編程教程_22_if 條件語句挑戰2
- 2020 年 8 月 7 日
- AI
- C/C++/C#
- 設計一個程式,用於統計得分
- 每次按下空格鍵加十分
- 分數達到 100 分以上,彈出消息:Great!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddPoints : MonoBehaviour
{
public int points = 0;
// 設置個變數存儲分數
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) // 判斷按下空格鍵
{
points += 10; // 加十分
Debug.Log("Points: " + points); // 顯示分數
}
if (points >= 100) // 分數達到 100分
{
Debug.Log("Great!"); // 彈出該消息
}
}
}
- 這裡你會發現 Great!會不斷顯示
- 那是因為 update() 裡面每秒運行 60次(即 60 幀),所以相當於每秒進行 60 次判斷,每次都成立,所以每秒顯示 60 次 Great!
- 試想一下,如何讓程式只顯示一次呢?