I made a class particle in C# and am trying to call the constructor to create another object from that class inside the list lstParticles. I'm not sure why I can't add an object to the list even if the list currently has no items.
The whole error was:
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)
Here's the code:
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]);
}
}
}
I tried adding an integer to the list with
lstParticles.Add(int 8);
//I also tried:
lstParticles.Add(8);
And got the same error.
Any suggestions on what I am doing wrong?
Edit: So Bing AI helped me figure this one out. I thought the list was occuring because of an error with lstParticles.Add(new particle(0, 0)); but it was actually with the constructor. In the constructer I put
pos[0] = x; pos[1] = y;
So it was trying to set the value of an index that didnt exist.
Bing AI suggested replacing it with
pos.Add(x); pos.Add(y);
which fixed everything (Thanks Bing)