Unity的C#編程教程_42_array 數組挑戰2 隨機選擇

  • 任務說明:
    • 設定 3 個列表,分別存放名字,等級,武器,3者一一對應
    • 隨機選取名字
    • 列印出該名字,及其等級和武器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArrayOverview : MonoBehaviour
{

    public string[] names = new string[] { "Magician", "Monk", "Hero", "Demon" };
    public int[] level = new int[] { 20, 18, 16, 33 };
    public string[] weapons = new string[] { "axe", "hand", "sword", "spear" };


    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            int id = Random.Range(0, names.Length);
            // 這裡隨機的右邊界設定為數組的長度,即為 4
            // 又邊界不包含在裡面,所以從 0,1,2,3 中隨機選取
            Debug.Log("The level of " + names[id] + " is " + level[id] + " and his weapon is " + weapons[id]);
        }
    }
}

這裡隨機的右邊界之所以使用 names.Length ,是因為這樣設置後,以後你改變數組的長度也不用再修改右邊界的程式碼了,而且不用去手動地數數組長度

Tags: