Spawning obstacles at runtime

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:

  1. Go to the Project tab and open up the 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.
  2. Once this is done, select the Obstacle objects from the Hierarchy tab and delete it because we won't need it anymore.
  3. Now that we have the obstacles, let's start spawning them. To do this, open up the 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;
  4. Next, add in the following function:
    /// <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);
    }
  5. Then, to have the function be called, add the following line to the end of the Start function:
        InvokeRepeating("CreateObstacle", 1.5f, 1.0f);
  6. Save the script and move back into the Unity editor. From the Hierarchy tab, select the GameController object and assign the Obstacle prefab to the Obstacle Reference property.
  7. Save your scene and start the game!
    Spawning obstacles at runtime

As you can see, we now have a number of different obstacles being created, each with their own different positions. Great!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset