- Home /
Space Shooter: How can I spawn the asteroids more than once?
When I run Space Shooter the asteroids spawn only once. When I press the 'R' key they spawn, but only once again. How can I make them spawn multiple times in the same run?
Answer by Cornelis-de-Jager · Feb 05, 2019 at 05:45 AM
There is a nice function for this exactly
using UnityEngine;
using System.Collections.Generic;
// Starting in 2 seconds.
// a projectile will be launched every 0.3 seconds
public class ExampleScript : MonoBehaviour
{
public Rigidbody projectile;
void Start()
{
InvokeRepeating("LaunchProjectile", 2.0f, 0.3f);
}
void LaunchProjectile()
{
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
}
Answer by yz09tech · Feb 05, 2019 at 02:55 PM
Thank you for your response. I added your script to the Game Controller in the Inspector and dragged the Asteroid object to the Projectile slot in the script. It didn't work. Then, I added the script to the Main Camera instead of the Game Controller. It didn't work. What am I doing wrong?
I got that of the Unity page. Below is the solution of how I will personally do it.
/* $$anonymous$$ain Variables */
private IEnumerator spawnFunction;// keep a copy of the executing script
public float timeBetweenSpawn = 1; // Default it to 1 seconds
public GameObject Astroid; // Drag a prefab from your asset folder onto here
/* Temp Variables */
public Vector3 position;
public Quaternion rotation;
void Start()
{
spawnFunction = SpawnAndWait();
StartSpawn();
}
public void StopSpawn() => StopCoroutine(spawnFunction);
public void StartSpawn () => StartCoroutine(spawnFunction);
IEnumerator SpawnAndWait()
{
while (true)
{
SpawnAstroid ();
yield return new WaitForSeconds(timeBetweenSpawn);
}
}
// Customize the spawn function as you like
void SpawnAstroid () {
var astroid = Instantiate (astroid, position, rotation) as GameObject;
/* Do $$anonymous$$ore things */
}
this way adds flexibility to stop and start when you like. Also the functions with the =>
are just one liners. If they don't work replace them with actual bracket functions { }
Answer by blueshark- · Feb 05, 2019 at 10:43 PM
Instantiate(projectile, startPos.transform.position, Quaternion.identity);
You could just try and call this multiple times and it should spawn it as many times as you call it.