Unity的C#编程教程_28_switch语句

  • switch 其实就是 else if 的替代品
  • 可以让代码更简洁清晰
  • 如果你用了 2 个或者以上的 eles if ,那就考虑下能否改成 switch
  • 比如一个游戏得分评价系统:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grade : MonoBehaviour
{

    public int score;
    public string show;

    // Start is called before the first frame update
    void Start()
    {
        score = Random.Range(0, 6); // 随机生成分数
    }

    // Update is called once per frame
    void Update()
    {
        if (score == 0) // 0分 差
        {
            show = "Bad";
        }
        else if (score == 1 || score == 2) // 1,2分 中等
        {
            show = "Normal";
        }
        else if (score == 3) // 3分 好
        {
            show = "Good";
        }
        else // 4,5 分为优秀
        {
            show = "Great";
        }


        if (Input.GetKeyDown(KeyCode.Space))
        {
            score = Random.Range(0, 6); // 按下空格键重置分数
        }
    }
}

  • 这里我们用 switch 替代就可以更为清晰
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grade : MonoBehaviour
{

    public int score;
    public string show; // 这里设置了 public 变量可以直接在 unity 窗口查看结果

    // Start is called before the first frame update
    void Start()
    {
        score = Random.Range(0, 6); // 随机生成分数
    }

    // Update is called once per frame
    void Update()
    {
        /*
        if (score == 0) // 0分 差
        {
            show = "Bad";
        }
        else if (score == 1 || score == 2) // 1,2分 中等
        {
            show = "Normal";
        }
        else if (score == 3) // 3分 好
        {
            show = "Good";
        }
        else // 4,5 分为优秀
        {
            show = "Great";
        }
        */

        
        switch (score)
        {
            case 0:
                show = "Bad";
                break;

            case 1:

            case 2:
                show = "Normal";
                break;

            case 3:
                show = "Good";
                break;

            default:
                show = "Great";
                break;

        }
        

        if (Input.GetKeyDown(KeyCode.Space))
        {
            score = Random.Range(0, 6); // 按下空格键重置分数
        }
    }
}

  • 注意,这里 switch 的 case 仅仅是用于“指定情况”,比如这里的 1,2,3,4 之类,但是如果换成“范围”,比如 2<a<5 就不能用在 switch 里面了
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值