How Do I Create a List in Unity?

How Do I Create a List in Unity?

When I create a list, I get this error: using the generic type system.collections.generic.list' requires 1' type argument(s)

Here is my code:

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()
    {
        
    }
} 
2

2 Answers

You need to declare which type your list has. E.g:

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

By the way you don't need to check :

if(namesOfDestroyedObjects.Count>0){}

On the first check of the for loop if "namesOfDestroyedObjects.Count" is not greater than 0 then the for loop will break right away.

0

Creating a list in c#:

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

You must specify the type of List<>. Like List<int> or List<Object>. Depending on your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.