Many games make use of spawn points and waypoints. This recipe demonstrates a very common example of spawning: choosing a random spawn point and instantiating an object at that point.
This recipe builds upon the player-controlled cube Unity project you created in the first recipe. So make a copy of that project, open it, and then follow the steps of this recipe.
To choose a random spawn point, perform the following steps:
// file: SpawnBall using UnityEngine; using System.Collections; public class SpawnBall : MonoBehaviour { public GameObject prefabBall; public GameObject[] respawns; public const float FIRE_DELAY = 0.25f; private float nextFireTime = 0f; private void Start(){ respawns = GameObject.FindGameObjectsWithTag("Respawn"); } void Update() { if( Time.time > nextFireTime ) CheckFireKey(); } void CheckFireKey() { if( Input.GetButton("Fire1")) { CreateSphere(); nextFireTime = Time.time + FIRE_DELAY; } } private void CreateSphere(){ int r = Random.Range(0, respawns.Length); GameObject spawnPoint = respawns[r]; if( spawnPoint ) Instantiate( prefab_ball, spawnPoint.transform.position, spawnPoint.transform.rotation); } }
Prefab-ball
, and drag your sphere into it (and then delete the sphere from the Hierarchy panel).SpawnBall
scripted component, drag Prefab-ball over the public variable Projectile Prefab-ball.Capsule-spawnPoint
at (3, 0.5, 3), give it the tag Respawn
(this is one of the default tags Unity provides) and uncheck its Mesh Renderer (so it is invisible).Capsule-spawnPoint
and move the copy to (-3, 0.5, -3).The two Capsule-spawnPoint
objects represent candidate locations where we might wish to create an instance of our ball Prefab. When the Start()
message is received, GameObject array respawns
is set to the array returned from the call to FindGameObjectsWithTag("Respawn")
. This creates an array of all objects in the scene with the tag Respawn
, that is, the two Capsule-spawnPoint
objects.
Variable nextFireTime
stores the time a projectile may be fired next, and for each frame the current time is tested to see if that time has been reached. If it has, the CheckFireKey()
method is called. This variable is initialized to zero, so the user doesn't have to wait at all to fire the first time.
The CheckFireKey()
method tests whether at that instant the user is pressing the Fire button. If the Fire button is pressed, the CreateSphere()
method is called. Also, the next time the player can fire is set to FIRE_DELAY
seconds in the future.
The CreateSphere()
method chooses a random index (r
) in the respawns
array and assigns the spawnPoint
variable to the GameObject at that location in the array. It then creates a new instance of prefab_Ball
(via the public variable) at the same position and rotation of the spawnPoint
.
18.191.139.169