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!
- 试想一下,如何让程序只显示一次呢?