- Home /
The question is answered, right answer was accepted
Problem with arrays in a list
I have made a class that contains an array of Vector3s and I try to add that array in a list. Nothing I've tried to do seems to solve this. I get an error every time that array is out of range. Any ideas?
[System.Serializable]
public class NodeClass
{
public Vector3[] location;
}
public List<NodeClass> allNodes;
parts = GameObject.FindGameObjectsWithTag("Part");
for (int i = 0; i < parts.GetLength(0); i++)
{
GameObject go = parts[i];
Part part = go.GetComponent<Part>();
Vector3[] nodes = part.nodeLocation;
allNodes[i] = new NodeClass();
for (int x = 0; x < nodes.GetLength(0); x++)
{
allNodes[i].location[x] = nodes[x];
}
}
Answer by Spip5 · Aug 15, 2020 at 11:59 AM
You script does not make much sense :P. At not point you add your nodes to your list, and i am confused as to why you are looping through your list again (inside your node loop) to basically re-put the same value ? Something like this would work, I guess ?
[System.Serializable]
public class NodeClass
{
public Vector3[] location;
public NodeClass(Vector3[] _locations)
{
location = _locations;
}
}
[...]
void test()
{
List<NodeClass> allNodes = new List<NodeClass>();
GameObject[] parts = GameObject.FindGameObjectsWithTag("Part");
for (int i = 0; i<parts.GetLength(0); i++)
{
GameObject go = parts[i];
Part part = go.GetComponent<Part>();
Vector3[] nodes = part.nodeLocation;
allNodes.Add(new NodeClass(nodes));
}
}
}
public class Part
{
public Vector3[] nodeLocation;
}
Exactly what I was trying to do. I'm still a bit beginner with C# and Unity so don't really understand how these things operate. Thank you!
No worries, everyone's a beginner at some point :). Unless you are adding other values in your NodeClass, you can even simplify your script more by making a list of Vector3 arrays directly, and not a list of NodeClasses
List<Vector3[]> allNodes = new List<Vector3[]>();
Follow this Question
Related Questions
How can you do calculations on two lists? 1 Answer
Undo/back system using a List/Array 2 Answers
Reading all data in the list with duplicate data inside 1 Answer
How to return index of List element? 1 Answer
How to modify array values? 1 Answer