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

Unity中C#列表添加对象触发索引越界异常的排查与解决

解决List添加对象时触发ArgumentOutOfRangeException异常的问题

异常信息

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].set_Item (System.Int32 index, T value) (at <88e4733ac7bc4ae1b496735e6b83bbd3>:0)
Particles+particle..ctor (System.Single x, System.Single y) (at Assets/Particles.cs:23)
Particles.Update () (at Assets/Particles.cs:45)

相关代码

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

public class Particles : MonoBehaviour
{
    public GameObject ParticleWater;
    bool Spawn = false;
    public List<particle> lstParticles = new List<particle> { };

    //Class defining particle
    public class particle {
        public List<float> pos = new List<float>();
        public List<float> posLast = new List<float>();
        public List<float> posNext = new List<float>();

        public particle(float x, float y)
        {
            pos[0] = x;
            pos[1] = y;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && Spawn == false)
        {
            Spawn = true;
        } else if(Input.GetKeyDown(KeyCode.Space) && Spawn == true)
        {
            Spawn = false;
        }
        if (Spawn)
        {
            lstParticles.Add(new particle(0, 0));
            //Debug.Log(particle[0]);
        }
    }
}

问题原因

异常根源在particle类的构造函数中:初始化的pos是一个空的List<float>,此时列表中没有任何元素,直接通过pos[0] = x、pos[1] = y的方式访问索引赋值,会触发索引越界——因为列表的当前长度为0,合法索引范围是空的,0和1都超出了有效范围。

解决方案

将构造函数中直接索引赋值的方式,改为使用List.Add()方法添加元素:

public particle(float x, float y)
{
    pos.Add(x);
    pos.Add(y);
}

这样就能正确将x、y的值添加到pos列表中,避免索引越界异常,进而正常向lstParticles列表中添加particle对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:43:29