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 裡面了
Tags: