-1

It's Unity C#. I have a problem with my code here. My goal is to keep cubePositions in a list which I'll use later. I am kepeeng it in a weird way. I used Vector3 but it gave me the same error. I am getting the error: ArgumentOutOfRange. My best guess is that the value replaces the last one. Also, all of my game objects called the same. print() is not a problem. Thank you!!! Here is my code:

public class MapAccess : MonoBehaviour
{
    List<float> cubePositionsX = new List<float>();
    List<float> cubePositionsZ = new List<float>();

    void Start()
    {

        foreach (GameObject cube in GameObject.FindGameObjectsWithTag("Cube"))
        {
            cubePositionsX.Add(cube.transform.position.x);
            cubePositionsZ.Add(cube.transform.position.z);

            print(cubePositionsX[0]);
            print(cubePositionsX[1]); //The problem is here. Unity said that ArgumentOutOfRange

        }
Maxim
  • 1
  • 1
  • You want to get the second element of the list although you only added only one value (x) to the list. y was added to another list – Stephan Bauer Jul 23 '21 at 14:19
  • 1
    cubePositionsX only have 1 element. – Magnetron Jul 23 '21 at 14:19
  • You are adding only one element to `cubePositionsX` so you can't access index `1` (which would be the second element) `z` is added to `cubePositionsZ` and can be accessed via `cubePositionsZ[0]` – derpirscher Jul 23 '21 at 14:19

1 Answers1

1

cubePositionsX has only one element when almost finishing the first iteration, you want to address the second here:

print(cubePositionsX[1]);

First add them, then print them or access them!

    foreach (GameObject cube in 
      GameObject.FindGameObjectsWithTag("Cube"))
    {
        cubePositionsX.Add(cube.transform.position.x);
        cubePositionsZ.Add(cube.transform.position.z);
    }

    print(cubePositionsX[0]); // or print(cubePositionsX.ElementAt(0));

    foreach (var item in cubePositionsX)
    {
        print(item);
    }

Regards

Martin.Martinsson
  • 1,894
  • 21
  • 25
  • Yes by the problem is, it shouldn’t. I have more than one object in the game with the same tag and by writing ‘print(cubePositionsX[1]’ I’m checking if there is a second object in the list. I don’t understand why the second object is not going in the list and there is only one all the time. Am I unsung ‘foreach’ in the wrong way? Thanks! – Maxim Jul 23 '21 at 16:15
  • @Maxim: Firstly add items sencondly print them by using a secondary loop or direct access! (updated code!) – Martin.Martinsson Jul 23 '21 at 18:18