Home > Enterprise >  Cannot use ArrayList in Unity, C#
Cannot use ArrayList in Unity, C#

Time:12-12

I try to use ArrayList to store a value but I don't know why it gets error.

using UnityEngine;

public class Example : MonoBehaviour
{
    ArrayList aList = new ArrayList();
    // Start is called before the first frame update
    void Start()
    {
        int i = 3;
        aList.Add(i); //error here
        Debug.Log(aList[0]);  //and here
    }

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

    }
}

when I create a C# script in Unity it has using System.Collections and using System.Colections.Generic but when I use Ctrl S to save those will disappear because IDE005: Using directive is unnecessary

And here is the error statement:

Error CS1061 'ArrayList' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'ArrayList' could be found (are you missing a using directive or an assembly reference?)

I don't know I'm missing any using directive or something.

CodePudding user response:

What class is that actually? Presumably it is not the System.Collections.ArrayList class, because that does have an Add method. If that's the class you meant to use then you need to make sure that you have imported the namespace or else you must qualify the type name. That said, you probably shouldn't be using that ArrayList class at all. Not sure whether it's a thing with Unity but, in .NET development generally, that class was effectively replaced by the List<T> in 2005.

CodePudding user response:

Try updating your Unity and Visual Studio, the below code worked perfectly for me. (Also ensure that you downloaded the Unity libraries in Visual Studios so you get better intellisense suggestions)

One last thing, if you have problems with classes then try to implicitly state your class

System.Collections.ArrayList a = new System.Collections.ArrayList();
a.Add("test");
  • Related