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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值