Unity的C#编程教程_44_遍历数组挑战:武器数据库

  • 任务说明:
    • 建立一个武器的类,包含武器的 id,武器名字,武器描述
    • 使该类在 unity 中可见
    • 建立一个武器的数组,存放多种武器

首先,建立新的武器类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable] // 设定一个类可以在 unity 中显示,但是该类无法继承
public class Weapon
{
    public int weaponID; // 包含id
    public string weaponName; // 名字
    public string weaponDescription; // 描述
}

public class ArrayOverview : MonoBehaviour
{


    public Weapon[] weaponList; // 新建一个数组,该数组里面的元素都是 Weapon 类


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

    // Update is called once per frame
    void Update()
    {
        
    }
}

保存脚本后,进入 unity 添加各种武器的 id,名字,和描述

比如:

id:0,name:None,description:None

id:1,name:Knife,description:Low damage

id:2,。。。

id:3,。。。

回到脚本中我们可以用 for 循环遍历并打印数组中的元素:

void Start()
{
  foreach (var item in weaponList)
  {
    Debug.Log(item.weaponID);
    Debug.Log(item.weaponName);
    Debug.Log(item.weaponDescription);
  }
}

按下空格键,打印随机的武器:

void Update()
{
  if (Input.GetKeyDown(KeyCode.Space))
  {
    int random_id = Random.Range(0, weaponList.Length);
    Debug.Log(weaponList[random_id].weaponID);
    Debug.Log(weaponList[random_id].weaponName);
    Debug.Log(weaponList[random_id].weaponDescription);
  }
}

同样,我们也可以在游戏初始化的时候检查对应 id 的武器是否存在:

    void Start()
    {
        foreach (var item in weaponList)
        {
            if(item.weaponID == 7) // 如果没有该序号,则不打印
            {
                Debug.Log(item.weaponID);
                Debug.Log(item.weaponName);
                Debug.Log(item.weaponDescription);
            }
        }
    }
Tags: