Spawning/Destroying objects inproperly
Hello
I've been trying to spawn several objects in 6 different spawnpoints. I've managed to spawn them successfully so far, but they were causing problem by overlapping each other. To prevent that I attached to all objects that I wanted to be spawned: a rigidbody (without gravity), small sphere collider (set as trigger) and made a class called 'StopOverlapping' that used OnTriggerEnter to check for collisions and respawn an object. Unfortunately It didn't work as intended - there were randomly from 0 to 6 objects spawned (mostly 0) even though I tried setting 'thingstospawn' variable to 100..
There should be 6 spawned every time.
Here's the code:
public class GameController : MonoBehaviour {
public Transform[] SpawnPoints;
public float spawnTime = 1f;
public GameObject[] items;
public int items_num;
public static int thingstospawn;
void Start()
{
Invoke ("Spawn", spawnTime);
thingstospawn = 6;
}
void Spawn ()
{
for (int i = 0; i < thingstospawn;) {
items_num = Random.Range (0, 5);
int spawnPointIndex = Random.Range (0, SpawnPoints.Length);
Instantiate (items [items_num], SpawnPoints [spawnPointIndex].position, SpawnPoints [spawnPointIndex].rotation);
i++;
}
}
}
and the 'StopOverlapping class:
public class StopOverlapping : MonoBehaviour {
void OnTriggerEnter(Collider other)
{
if (tag == "Item") {
GameController.thingstospawn = GameController.thingstospawn +1;
Destroy(gameObject);
}
}
}
Your answer
Follow this Question
Related Questions
Can someone help me add a wave to my Spawner script!!! 0 Answers
Random.value for each GameObject. 1 Answer
How to spawn a prefab every 5 second randomly between a set range? 0 Answers
Why do I keep getting 'The object you want to instantiate is null' warning? 1 Answer
how to Spawn prefab infront off player and destroy it when hr passed it 0 Answers