unity3d 如何给List 添加结构体struct

分类栏目:unity3d教程

117

unity3d如何给list 添加结构体struct

在Unity3D中,要将struct添加到List中,你可以使用List的泛型类型。以下是一个简单的示例,演示如何在List中添加自定义的struct

代码如下

using System.Collections.Generic;
using UnityEngine;

// 定义一个结构体
public struct MyStruct
{
    public int id;
    public string name;
}

public class StructListExample : MonoBehaviour
{
    // 创建一个List,其元素是MyStruct类型
    private List<MyStruct> myStructList = new List<MyStruct>();

    void Start()
    {
        // 创建一个结构体实例并添加到List中
        MyStruct struct1 = new MyStruct { id = 1, name = "Struct 1" };
        myStructList.Add(struct1);

        // 创建另一个结构体实例并添加到List中
        MyStruct struct2 = new MyStruct { id = 2, name = "Struct 2" };
        myStructList.Add(struct2);

        // 遍历List并在控制台中打印结构体的属性
        foreach (MyStruct myStruct in myStructList)
        {
            Debug.Log("ID: " + myStruct.id + ", Name: " + myStruct.name);
        }
    }
}