You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中使用ArrayList报错求助:无法找到Add方法

问题解决:Unity中ArrayList报错CS1061的修复方案

直接修复当前问题

你的报错核心是缺少System.Collections命名空间引用,IDE因为误判自动移除了该引用,导致编译器无法识别ArrayList的完整定义。

  1. 手动在脚本顶部添加using System.Collections;,也可以添加注释阻止IDE自动移除:
using UnityEngine;
using System.Collections; // 手动添加,确保ArrayList能被正确识别

public class Example : MonoBehaviour
{
    ArrayList aList = new ArrayList();
    void Start()
    {
        int i = 3;
        aList.Add(i);
        Debug.Log(aList[0]);
    }

    void Update()
    {

    }
}
  1. 若IDE仍自动移除该引用,可在Unity编辑器设置中调整:
    • 打开Edit > Preferences > External Tools
    • 找到对应IDE的设置项,关闭“移除未使用的Using指令”类的自动清理功能(不同IDE选项名称略有差异)

推荐的替代方案:使用泛型List

ArrayList是C#早期的非泛型集合,存在类型不安全、装箱拆箱性能损耗的问题,Unity官方更推荐使用泛型List<T>,它属于System.Collections.Generic命名空间(你的脚本初始生成时已包含,且不会被IDE误判移除)。

修改后的代码示例:

using UnityEngine;
using System.Collections.Generic; // 该命名空间默认保留

public class Example : MonoBehaviour
{
    List<int> aList = new List<int>(); // 指定存储int类型,类型更安全
    void Start()
    {
        int i = 3;
        aList.Add(i);
        Debug.Log(aList[0]);
    }

    void Update()
    {

    }
}

报错原因说明

IDE提示的IDE005: Using directive is unnecessary是误判:在你保存脚本时,IDE还未完成ArrayList的代码解析,误以为System.Collections没有被使用,所以自动移除了该引用。移除后编译器找不到ArrayList的正确类定义,将其视为空的自定义类,自然找不到Add方法,从而抛出CS1061错误。

内容的提问来源于stack exchange,提问作者user20708378

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:46:12