Now that we have a simple obstacle, we can now spawn a number of them through code using this object as a reference. To make this easier, let's make the obstacle a prefab:
Prefabs
folder. Then, from the Hierarchy tab, drag and drop the Obstacle
object into the Project tab's Prefabs
folder. The obstacle object should turn the object.Obstacle
objects from the Hierarchy tab and delete it because we won't need it anymore.GameController
script and add the following variables:[Header("Obstacle Information")] [Tooltip("The obstacle that we will spawn")] public GameObject obstacleReference; [Tooltip("Minimum Y value used for obstacle")] public float obstacleMinY = -1.3f; [Tooltip("Maximum Y value used for obstacle")] public float obstacleMaxY = 1.3f;
/// <summary> /// Creates the obstacle an initializes its position. /// </summary> void CreateObstacle() { // Spawn offscreen with a random Y Instantiate(obstacleReference, new Vector3(RepeatingBackground.ScrollWidth, Random.Range(obstacleMinY, obstacleMaxY), 0.0f), Quaternion.identity); }
InvokeRepeating("CreateObstacle", 1.5f, 1.0f);
GameController
object and assign the Obstacle
prefab to the Obstacle Reference property.As you can see, we now have a number of different obstacles being created, each with their own different positions. Great!