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
,是因为这样设置后,以后你改变数组的长度也不用再修改右边界的代码了,而且不用去手动地数数组长度