Unity的C#编程教程_23_if 条件语句挑战3

  • 设计一个程序,用于统计得分
  • 每次按下空格键加十分
  • 分数达到 100 分以上,弹出消息:Great!(限制为仅仅弹出一次)
  • 提示:使用 bool 变量
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AddPoints : MonoBehaviour
{
    public int points = 0;
    // 设置个变量存储分数
    private bool _getPoint;
    // 表示之前没有达到过,默认为 false

    // 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 && !_getPoint) // 分数达到 100分 并且之前没有达到过
        {
            _getPoint = true; // 把状态切换到:已经到达过
            Debug.Log("Great!"); // 弹出该消息
        }
    }
}

Tags: