unity中各种集合类,如 List、Dictionary、Queue ,链表,队列,堆栈,帮我写一个案例把unity中各种集合都使用一次
时间: 2024-03-27 07:36:34 浏览: 12
好的,以下是一个使用Unity中各种集合类的案例:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectionsUsageExample : MonoBehaviour
{
// 定义List集合
private List<int> numList = new List<int>();
// 定义Dictionary集合
private Dictionary<string, int> dict = new Dictionary<string, int>();
// 定义Queue队列
private Queue<string> msgQueue = new Queue<string>();
// 定义LinkedList链表
private LinkedList<string> nameList = new LinkedList<string>();
// 定义Stack堆栈
private Stack<float> numStack = new Stack<float>();
void Start()
{
// 向List集合中添加元素
numList.Add(1);
numList.Add(2);
numList.Add(3);
// 向Dictionary集合中添加键值对
dict.Add("apple", 5);
dict.Add("banana", 3);
dict.Add("orange", 2);
// 向Queue队列中添加元素
msgQueue.Enqueue("Hello");
msgQueue.Enqueue("World");
// 向LinkedList链表中添加元素
nameList.AddLast("Alice");
nameList.AddLast("Bob");
nameList.AddLast("Charlie");
// 向Stack堆栈中添加元素
numStack.Push(1.1f);
numStack.Push(2.2f);
numStack.Push(3.3f);
}
void Update()
{
// 遍历List集合
foreach (int num in numList)
{
Debug.Log("num: " + num);
}
// 遍历Dictionary集合
foreach (KeyValuePair<string, int> pair in dict)
{
Debug.Log(pair.Key + ": " + pair.Value);
}
// 弹出Queue队列中的元素
if (msgQueue.Count > 0)
{
Debug.Log(msgQueue.Dequeue());
}
// 遍历LinkedList链表
LinkedListNode<string> node = nameList.First;
while (node != null)
{
Debug.Log(node.Value);
node = node.Next;
}
// 弹出Stack堆栈中的元素
if (numStack.Count > 0)
{
Debug.Log(numStack.Pop());
}
}
}
```
这个案例演示了如何使用Unity中的各种集合类,包括List、Dictionary、Queue、LinkedList和Stack。在Start方法中,我们向这些集合中添加了一些元素;在Update方法中,我们遍历了这些集合,并弹出了一些元素。您可以根据自己的需求对这个案例进行修改和扩展。