Making Objects Fall Random On The Screen in Unity

How to spawn object on the screen in Unity Randomly?

I am currently developing with a friend o mine a game. It’s called Badger Adventures. It’s a very simple game in which you are collecting Apples with an Badger.

So… how do you spawn apples randomly?

Actually, if you are an experienced user than you just need to check out the Random.range function which is built in Unity3d Library.

 

Otherwise check out my Script. It’s called AppleSpawn and well… it is spawning Apples.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AppleSpawn : MonoBehaviour {

  public GameObject apple;			// Apple Object in Scene (Sprite)
  public GameObject badApple;			// Bad Apple Object in Scene (Sprite)

  public float spawnTime = 2f;            // How long between each spawn.
  public float fallSpeed = 40.0f;		//The speed of falling Apples

  private float timer = 0; //counting timer, reset after calling SpawnRandom() function
  private int randomNumber; 			//variable for storage of an random Number
  
  void Update () {

    timer += Time.deltaTime;   // Timer Counter
    if(timer>spawnTime){
      SpawnRandom(); 			//Calling method SpawnRandom()
      timer = 0;				//Reseting timer to 0
    }

  }

  public void SpawnRandom()
  {
  
      //Creating random Vector3 position
    Vector3 screenPosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0,Screen.width), Random.Range(600 ,Screen.height), Camera.main.farClipPlane/2));

    //Instantiation of the Apple Object
    Instantiate(apple,screenPosition,Quaternion.identity);
  }

}

In the update function there is an if statement because i wanted to restrict the number of spawned Apples. If i want to create more apples i can change the variable in the public function from 2 to 0.2. For the time counting i used Time.deltaTime because this function is frame rate independent.

SpawnRandom() method is creating an random Vector3 value on the top of the screen depending on the Screen Size (Camera) Width and Height.

If we wanted for example to place the spawned elements little lower on the screen we can change the number from 600 to 400. In your example the variable can be a little different depending on the screen size you are developing.

Instatiate just spawns the object on the scene.

That’s all. Thanks for Reading.

Leave a Reply

Your email address will not be published. Required fields are marked *