在 Unity 代码中使用数组和列表

数组 和列表是Unity 中有用的数据结构,允许您存储和操作元素 的集合。它们提供了管理同一类型的多个值的灵活性。以下是使用数组和列表的概述:

数组

数组是相同 type 的元素的固定大小集合。数组的大小在声明时确定,不能动态更改。以下是在 C# 中声明和使用数组的示例:

// Declaring an array of integers
int[] numbers = new int[5];

// Assigning values to array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Accessing array elements
int firstElement = numbers[0];
int thirdElement = numbers[2];

// Iterating through an array
for (int i = 0; i < numbers.Length; i++)
{
    Debug.Log("Element at index " + i + ": " + numbers[i]);
}

在此示例中,声明了一个名为 'numbers' 的整数数组,其大小为 5。使用索引表示法 ('numbers[index]') 将值分配给各个数组元素。使用各自的索引来访问和修改数组元素。

列表

列表是元素的动态集合,可以根据需要在 size 中增长或缩小。与数组相比,它提供了额外的功能和灵活性。下面是在 C# 中声明和使用列表的示例:

// Import the System.Collections.Generic namespace
using System.Collections.Generic;

// Declaring a list of strings
List<string> names = new List<string>();

// Adding elements to the list
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");

// Accessing list elements
string firstElement = names[0];
string lastElement = names[names.Count - 1];

// Iterating through a list
foreach (string name in names)
{
    Debug.Log("Name: " + name);
}

在此示例中,使用类 'List<T>' 声明字符串 'names' 的列表。使用 'Add' 方法将元素添加到列表中。列表元素也可以使用索引符号来访问和修改。'Count' 属性返回列表中的元素数量。loop'foreach' 变体用于迭代列表并对每个元素执行操作。

结论

数组和列表是通用的数据结构,使您能够有效地处理数据集合。根据您的要求,在数组(对于固定大小集合)和列表(对于动态集合)之间进行选择,以存储和操作用 Unity 编写的 code 中的数据。

推荐文章
Unity实现脚步声
在 Unity 中实现对象池
在 Unity 中创建子弹时间效果
在 Unity 中创建交互式对象
在 Unity 中实现动力学交互
在 Unity 中使用特定钥匙打开抽屉和橱柜
在 Unity 中添加玩家进入汽车