0

For a bit of context, I am trying to generate a random game object at a random position. I want to check if the distance between the random position and positions of pre-existing objects is at least the size of the player. If not then the random positon should be generated again. If the distance is greater than the size of the player then the object should be instantiated and added to created objects. However I am getting an index out of range error and I am unsure where and why.

int numberOfPillars = Random.Range(1,3);
for (int i = 0; i < numberOfPillars; i++)
    {
        Vector3 randomPos;
        while (numberOfPillars != createdObjects.Count)
        {
            Debug.Log(createdObjects.Count);
            randomPos = new Vector3(Random.Range(-12f, 12f), Random.Range(-7f, 7f), 0f);
            for (int x = 0; x <= createdObjects.Count; x++)
            {
                if (Mathf.Abs(createdObjects[x].x - randomPos.x) >= playerSize || Mathf.Abs(createdObjects[x].y - randomPos.y) >= playerSize)
                {
                    if (x == createdObjects.Count)
                    {
                        int selectedPillar = Random.Range(0, 4);
                        Instantiate(pillars[selectedPillar], randomPos, Quaternion.identity);
                        createdObjects.Add(randomPos);
                    }
                }
            }
        }
    }
  • Are you sure there are at least 4 gameObjects in your `List pillars`? – IndieGameDev Dec 01 '20 at 10:27
  • @MathewHD Yup, that part is perfectly fine. – Hruday Sasank Yadavalli Dec 01 '20 at 10:30
  • 1
    Could you tell me the exact line of the error? – IndieGameDev Dec 01 '20 at 10:31
  • @MathewHD No particular line is specfified. The error I get within the inspector is: ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. – Hruday Sasank Yadavalli Dec 01 '20 at 10:33
  • In general bit looks very dangerous! You are adding new items to `createdObjects` within a `for` loop (so possible multiple at once) but in your `while` condition you check for an exact count match with `numberOfPillars`. What if in the first iteration you have `numberOfPillara = 2` and `createdObjects.Count = 1` and then you add two new items? Then you have `createdObjects.Count = 3` and never exit the loop ... – derHugo Dec 01 '20 at 19:34

0 Answers0