unity c# List列表操作

1、List的基础、常用方法:

(1)、声明: 
①、List<T> mList = new List<T>();  
T为列表中元素类型,现在以string类型作为例子

List<string> mList = new List<string>();

②、List<T> testList =new List<T> (IEnumerable<T> collection);

以一个集合作为参数创建List:

string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };
List<string> testList = new List<string>(temArr);

(2)、添加元素:

①、 添加一个元素

  语法: List. Add(T item)  

List<string> mList = new List<string>();
mList.Add("John");

②、 添加一组元素

  语法: List. AddRange(IEnumerable<T> collection)   

List<string> mList = new List<string>();
string[] temArr = { "Ha","Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku",  "Locu" };
mList.AddRange(temArr);

③、在index位置添加一个元素

  语法: Insert(int index, T item); 

List<string> mList = new List<string>();
mList.Insert(1, "Hei");

④、遍历List中元素

语法:

foreach (T element in mList)  //T的类型与mList声明时一样
{
    Console.WriteLine(element);
}

例:

复制代码

复制代码

List<string> mList = new List<string>();
...//省略部分代码
foreach (string s in mList)
{
    Console.WriteLine(s);
}

复制代码

Unity C# 中,你可以使用 List<T> 类型创建一个循环列表。下面是一个示例代码: ```csharp using System.Collections.Generic; using UnityEngine; public class CircularList<T> { private List<T> list; private int currentIndex = 0; public CircularList(List<T> list) { this.list = list; } public T Next() { if (currentIndex == list.Count - 1) { currentIndex = 0; } else { currentIndex++; } return list[currentIndex]; } public T Previous() { if (currentIndex == 0) { currentIndex = list.Count - 1; } else { currentIndex--; } return list[currentIndex]; } public T Current() { return list[currentIndex]; } public void SetCurrentIndex(int index) { currentIndex = index; } } ``` 这个类接受一个 List<T> 对象作为参数,并提供了三个方法:Next(), Previous() 和 Current()。Next() 方法返回下一个元素,Previous() 方法返回上一个元素,Current() 方法返回当前元素。这些方法通过维护一个 currentIndex 变量来跟踪当前元素的索引。如果当前索引到达列表的末尾或开头,它将循环回到另一端。 你可以使用这个类来创建一个循环列表并遍历它的元素,例如: ```csharp using System.Collections.Generic; using UnityEngine; public class Example : MonoBehaviour { public List<string> items = new List<string>() { "A", "B", "C", "D" }; private CircularList<string> circularList; void Start() { circularList = new CircularList<string>(items); Debug.Log(circularList.Current()); // 输出 "A" Debug.Log(circularList.Next()); // 输出 "B" Debug.Log(circularList.Next()); // 输出 "C" Debug.Log(circularList.Previous()); // 输出 "B" circularList.SetCurrentIndex(3); Debug.Log(circularList.Current()); // 输出 "D" } } ``` 这个例子创建了一个字符串列表并将其传递给 CircularList<T> 类。然后,它使用 CircularList<T> 的方法来遍历列表,并输出每个元素的值。你可以使用 SetCurrentIndex() 方法来设置当前元素的索引。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值