- Home /
,Can i use InvokeRepeating to spawn just 1 GameObject at a time?
I'm trying to spawn collectible coins randomly within my game, and i have managed to get this working by doing the following:
public GameObject coin; // prefab to be spawned
public Transform[] spawnPosition; // creates ref which is used in line 18
public float spawnWait = 3.0f; // time between each spawn
void Start()
{
InvokeRepeating("Spawn", spawnWait, spawnWait);
}
void Spawn()
{
int spawnIndex = Random.Range(0, spawnPosition.Length);// create int between no. of spawnpositions
Instantiate(coin, spawnPosition[spawnIndex].position, spawnPosition[spawnIndex].rotation);
}
However, this does not fit the purpose of my game.
I only want to have 1 coin in play at a time, whereas this code will spawn a new coin every 3 seconds. This code will also sometimes spawn coins on top of one another when left to run for too long.
Is it possible to recall this function only after the previously cloned GameObject has been destroyed?
I have tried adding an if statement of (!=coin) within the spawn() function, but this does not work so I'm not even sure whether this is even the correct logic!
As you can probably tell, I'm a complete beginner and so any advise would be awesome!
Answer by Captain_Pineapple · Nov 17, 2018 at 05:00 PM
Hey there,
the probably easiest solution would be pack the span function in your coin. When you pick it up use 'Invoke()' instead of invokerepeating and spawn one after 3 seconds.
An even better solution would be to have your current spawn function be callable from your coin. On picking it up you notify your "Gamemanager" to disable your coin and reable it after 3 seconds. Instatiating is performance hungry. En/Disabling is not
If it's not really clear what i mean let me know and i'll try to specify.