0
\$\begingroup\$

I am very much a novice to coding with no background on this at all so the code you see here may be terrible.

Basically I’m making an endless runner, made up of a player character and a set of obstacle prefabs. The obstacle prefabs have a trigger on them so that when the player hits it, it spawns the next prefab. I’m using the code below, and when the player hits the first spawn trigger it will spawn a prefab, but on tripping the next trigger it gives me the ArgumentOutOfRangeException error in the console and doesn’t spawn anything.

public class ObsTrigger : MonoBehaviour {

 public GameObject spawnTrigger;
 [SerializeField] private List<Transform> obstacleList;

 private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.CompareTag("Player"))
     {
         for (int i = 0; i < obstacleList.Count; i++)
         {
             spawnObstacle();
         }
     }
 }

 public void spawnObstacle()
 {
     {
         Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
         Instantiate(chosenLevelPart);
     }
 }

}

If anyone can point me in the right direction I would really appreciate it!

\$\endgroup\$
  • \$\begingroup\$ just write obstacleList.Count-1 as arrays and list start from 0 to count-1 \$\endgroup\$ – virtouso Dec 1 '19 at 8:05
  • \$\begingroup\$ There is nowhere in this code that Count - 1 would be an effective fix, @virtouso. The for loop is already testing < Count, and the integer version of Random.Range selects values between min and max - 1 already. \$\endgroup\$ – DMGregory Dec 1 '19 at 15:26
1
\$\begingroup\$

In the following chunk of code, you should check if there are any elements in your obstacle list before you try to access them

public void spawnObstacle()
{
    Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
    Instantiate(chosenLevelPart);
}

should be

public void spawnObstacle()
{
    if (obstalceList.Count > 0)
    {
        Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
        Instantiate(chosenLevelPart);
    }
}

because if there are no objects in the list, obstacleList[0] will still attempt to access the first element of the list, which would then be out of range.

\$\endgroup\$
  • \$\begingroup\$ That makes sense, I’ve amended the code to what you suggested and the error message doesn’t pop up any more, but it still doesn’t spawn another prefab after collision. \$\endgroup\$ – C-delb Dec 2 '19 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.