I have run into a problem with my game. In my game, there is an gameobject called helicopter. There are also multiple scene prefabs that are randomly chosen from a list, and then spawned. This all works great. However, what I want to also happen is every time the helicopter collides with the 2d trigger box collider on the scene prefab, a new scene is randomly chosen from the list and spawned. This somewhat works. What keeps on happening is about 100 - 200 new scenes are spawned in front of one.
Solutions that I have tried:
I have already tried using a for loop, and using the list.count method.
Code for spawning the first Scene:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpawnScene : MonoBehaviour {
List<GameObject> prefabList = new List<GameObject>();
public GameObject Scene1;
public GameObject Scene2;
public GameObject Scene3;
// Use this for initialization
void Start () {
SpawnTheScene ();
}
public void SpawnTheScene () {
prefabList.Add (Scene1);
prefabList.Add (Scene2);
prefabList.Add (Scene3);
int prefabeIndex = UnityEngine.Random.Range (0, 3);
Instantiate (prefabList [prefabeIndex], new Vector3 (0.04f, 0, 0), Quaternion.identity);
}
// Update is called once per frame
void Update () {
}
}
Code for respawning the scene:
using UnityEngine;
using System.Collections;
public class SceneBehaviour : MonoBehaviour {
public SpawnScene spawnScene;
// Use this for initialization
void Start () {
}
void OnTriggerEnter2D (Collider2D col) {
if (col.gameObject.tag == "Helicopter") {
spawnScene.SpawnTheScene ();
}
}
// Update is called once per frame
void Update () {
}
}
Image of what happens in the hierarchy:
