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

Unity中设置自定义集合变量时触发ArgumentException异常求助

Unity问题:GetComponent调用List类型报错+变量变化触发方法实现

问题情况

我要实现仅在变量变化时调用Generate()函数,不用每帧检查,但设置变量时出现了这个错误:

ArgumentException: GetComponent requires that the requested component 'List`1' derives from MonoBehaviour or Component or is an interface

相关脚本代码

public GameObject CEMM;

private int ListLength;

public static int ListLengthProperty
{
    get
    {
        return JLSV.instance.ListLength;
    }
    set
    {
        JLSV.instance.ListLength = value;
        JLSV.instance.Generate();
    }
}

private void Awake()
{
    instance = this;
}

触发错误的赋值代码

JLScrollView.ListLengthProperty = JLScrollView.instance.CEMM.GetComponent<List<JLClass>>().Count;

解决办法

错误根源

GetComponent<T>()只能用来获取Unity的组件——也就是继承自MonoBehaviour、Component的类,或者接口类型。List<JLClass>是普通的C#泛型集合,不属于Unity组件范畴,所以用GetComponent去拿肯定报错。

修正步骤

如果你的List<JLClass>是存在于CEMM对象上某个脚本里的成员变量,得先获取那个脚本组件,再访问List:
举个例子,假设存List的脚本叫JLDataHolder,代码改成这样:

// 先获取目标脚本组件
var dataScript = JLScrollView.instance.CEMM.GetComponent<JLDataHolder>();
// 再访问脚本里的List并取Count
JLScrollView.ListLengthProperty = dataScript.MyJLClassList.Count;

这里的MyJLClassList就是JLDataHolder脚本中定义的List<JLClass>变量。

另外,你用静态属性触发Generate()的思路是对的,注意确保JLSV.instance在赋值前已经初始化(比如Awake里的单例赋值没问题),避免空引用错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:40:08