I have a spawn function which is

public void spawnobstacle(){
    number_of_spawn = Random.Range (1, 3);
        if (number_of_spawn > 0) {
            spawnposition = Random.Range (0, 3);
            if (spawnposition == 0 && !rightisoccupied) {
                Instantiate (obstacle, rightpos, Quaternion.identity);
                rightisoccupied = true;
            if (spawnposition == 1 && !midisoccupied) {
                Instantiate (obstacle, midpos, Quaternion.identity);
                midisoccupied = true;
                if (spawnposition == 2 && !leftisoccupied) {
                Instantiate (obstacle, leftpos, Quaternion.identity);
                leftisoccupied = true;
            number_of_spawn -= 1;

and I have another script in the obstacle GameObject that if the obstacle is triggered by it, it destroys the obstacle and spawn some other obstacle.

The content of the script is this:

public class DestroyObstacle : MonoBehaviour {
public GameObject world;
void OnTriggerEnter2D (Collider2D thecollision){
    if (thecollision.gameObject.tag == "destroypoint1") {

        world.GetComponent<Spawn> ().spawnobstacle ();
        Destroy (this.gameObject);
void Start(){
    world = GameObject.Find ("World");
void Update() {


Why is the function only calls one obstacle every time and the function is called only once, 2 times max (not every time the obstacle is destroyed)?


1 Answer 1


You don't seem to clear the rightisoccupied midisoccupied and leftisoccupied flags when an obstacle is destroyed.

One option would be to add a variable to the spawned obstacles which state the lane they are on. Have the DestroyObstacle check that variable and clear the corresponding flag in Spawn before calling .spawnobstacle ().

Another option would be to replace these flags with a reference to the actual game object. When you destroy a game object, it will be equal to null. So when you Destroy the rightObstacle and then call .spawnobstacle(), rightObstacle == null will be true.

  • \$\begingroup\$ I love you, you glorious person. \$\endgroup\$
    – Hubaka Gs
    Commented Aug 7, 2017 at 0:35

You must log in to answer this question.

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