2D: Spawning prefabs at random points above the screen?
I have a game where asteroids are spawning from the top just out of camera view falling down and you have to avoid them. I'm having trouble getting them to spawn. From reading and watching videos, It looks like that I'm supposed to make a prefab for the asteroid, then create an empty GameController. Within that GameController, I've created an empty GameObject and dragged my asteriod prefab into that spot. In the script, I reference the name of the prefab but it doesn't spawn. I know it's probably something simple that I'm just overlooking, or I'm not approaching this from the right way. (I wouldn't be surprised because this is my first time messing with Unity.)
Here's my script:
public class GameController : MonoBehaviour { public GameObject hazard; // Asteroid is placed in this on the inspector
void start() { SpawnWaves(); }
void SpawnWaves() { Vector3 spawnPosition = new Vector3(); // creates a new position to spawn object
Quaternion spawnRotation = new Quaternion(); // quaternion is spawn rotation, check for 2d objects.
Instantiate(hazard, spawnPosition, spawnRotation); // used to spawn the asteroid also known as hazard.
}
}
Answer by Jedd117 · Mar 18, 2016 at 03:37 AM
Thanks for the response! I was reading more after I posted this and I changed my code some. Here it is if any new people need something to start with. I've added comments to explain some of the code.
Script (c#):
public class GameController : MonoBehaviour {
public GameObject hazard;
void Start()
{
SpawnWaves();
}
void SpawnWaves()
{
Vector3 position = new Vector3(Random.Range(-8.5f, 8.5f), 8, 0); // creates a new position to spawn object created this by getting the "x" and "y" positions.
Instantiate(hazard, position, Quaternion.identity); // hazard is prefab, position declared variable above. Quanternion is the spin. By addeding "identity", it's set to none.
}
}