Home > Net >  How to init a list?
How to init a list?

Time:07-14

I use List to store my data, but the compiler says "Index was out of range. Must be non-negative and less than the size of the collection."

how can I init the list like myvector3 = new Vector3[65];

I use

public Vector3[] myvector3;

public Quaternion[] myQuaternion;

then

myvector3 = new Vector3[65];

myQuaternion = new Quaternion[65];

is ok....

public List<GameObject> Stroeallobject;
public List<Vector3> myvector3;
public List<Quaternion> myQuaternion;

private void Start()
{
for (int i = 0; i < Stroeallobject.Count; i  )
{
  myvector3[i] = Stroealljoint[i].transform.position;
  myQuaternion[i] = Stroealljoint[i].transform.rotation;
}
}

CodePudding user response:

Unlike an array, a List<> doesn't need to be initialized to a given length. You can simply instantiate it:

public List<Vector3> myvector3 = new List<Vector3>();

(Though it seems from the specific error message that is already being done elsewhere? Otherwise I would have expected a NullReferenceException. But either way...)

And then add items to it:

myvector3.Add(Stroealljoint[i].transform.position);

(The same is true of the other List<> object(s) of course.)

CodePudding user response:

You create the list variable with

public List<Vector3> myvector3;

but it's null after that, because you didn't assign it anything. You can make a new empty list later with

myvector3 = new List<Vector3>();

and you can also give it a capacity so it doesn't need to keep dynamically resizing the list as you add things to it:

myvector3 = new List<Vector3>(65);

but setting the capacity doesn't make anything. You're just saying you need the space for 65 Vector3 entries in the list. You can't assign anything into an index at this point because the list is empty.

It's not until you .Add() something to the list that you're allowed to index into it. This is different than an array.

Fortunately it's an easy fix for your code - change the index operation to an Add (and initialize the List) and you should be good to go!

public List<GameObject> Stroeallobject;
public List<Vector3> myvector3;
public List<Quaternion> myQuaternion;

private void Start()
{
    myvector3 = new List<Vector3>(); // Can use Stroealljoint.Count for capacity if you want
    myQuaternion = new List<Quaternion>();
    for (int i = 0; i < Stroeallobject.Count; i  )
    {
        myVector3. Add(Stroealljoint[i].transform.position);
        myQuaternion.Add(Stroealljoint[i].transform.rotation);
    }
}
  • Related