0
\$\begingroup\$

just at a bit of an impasse with this one if anyone can help.

I am developing an endless runner, and I am trying to instantiate my obstacle prefabs by having my player go through a trigger which activates an instantiation. The problem I'm having is that when the player goes through the trigger, my code seems to instantiate multiple prefabs at a time. I'll post screenshots and my code to illustrate this better.

Player hits the first trigger, instantiating 3 clones

Player hits the next trigger which instantiating even more clones

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObsGenerator : MonoBehaviour
{

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

    public Transform spawnLocation;

    public void OnTriggerEnter2D(Collider2D Player)
    {
        if (Player.CompareTag("Respawn"))
        {
           // for (int i = 0; i < obstacleList.Count; i++)
            {
                spawnObstacle();

            }
        }
    }

    public void spawnObstacle()
    {
        for (int i = 0; i < obstacleList.Count; i++)

            if (obstacleList.Count > 0)
            {
                Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count)];
                Instantiate(chosenLevelPart);
            }
        }
    }

Really appreciate anybody's help!

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

When you enter the trigger and spawn the obstacle you then were looping through and spawning once for every item in the obstacle list

public void OnTriggerEnter2D(Collider2D Player)
{
    if (Player.CompareTag("Respawn"))
    {          
            spawnObstacle();                            
    }
}

public void spawnObstacle()
{        
        if (obstacleList.Count > 0)
        {
            Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count)];
            Instantiate(chosenLevelPart);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ That’s solved it, looking back I have no idea why I put that for loop in, but I’ve removed it and it’s working perfectly now. Thanks for your comment! \$\endgroup\$
    – C-delb
    Dec 9, 2019 at 16:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .