如何在Unity中创建列表?

问题描述

创建列表时,出现此错误:使用泛型类型system.collections.generic.list'需要1'类型参数

这是我的代码

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


public class DestroyPotionForever : MonoBehavIoUr
{
    public static List namesOfDestroyedobjects = new List();
    // Start is called before the first frame update
    void Start()
    {
        if(namesOfDestroyedobjects.Count>0){

            for (int i = 0; i < namesOfDestroyedobjects.Count; i++) {
                Destroy(GameObject.Find(namesOfDestroyedobjects[i]));
            }
        }
    }
    void OnTriggerEnter(){
        namesOfDestroyedobjects.Add(this.gameObject.name);
        Destroy(this.gameObject);
    }

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

解决方法

您需要声明列表具有哪种类型。例如:

public static List<string> namesOfDestroyedObjects = new List<string>();

通过这种方式,您无需检查:

if(namesOfDestroyedObjects.Count>0){}

在for循环的第一次检查中,如果“ namesOfDestroyedObjects.Count”不大于0,则for循环将立即中断。

,

在c#中创建列表:

public static List<T> listName = new List<T>();

您必须指定List<>的类型。像List<int>List<Object>。根据您的需求。