How to create object falling from sky CONTINUOUSLY

I’m creating a fighter jet game
Player will fly and destroy enemy

How to make object CONTINUOUSLY (endless - auto generate after a delay) falling from a random position in sky

1 Answer

1

The simplest way would probably be to have a coroutine on an object that instantiates objects at random intervals with random x coordinates:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectSpawner : MonoBehaviour
{
	public GameObject rockPrefab;
    // Start is called before the first frame update
    void Start()
    {
	    StartCoroutine(SpawnRocks());
    }

	IEnumerator SpawnRocks()
	{
		while(true)
		{
			float randomTime = Random.Range(2f,5f);
			float randomPosition = Random.Range(-10f,10f);
			
			yield return new WaitForSeconds(randomTime);
			Instantiate(rockPrefab,new Vector3(randomPosition,transform.position.y,transform.position.z),Quaternion.identity);
		}
	}
	
}

If you put that on an object it should start spawning whatever you set in the “RockPrefab” variable.

For having the things fall down the screen, I’d put this code on whatever the thing is that’s meant to be falling:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rock : MonoBehaviour
{
	public float moveSpeed = 0.05f;
	public float timeout = 5f;
    // Start is called before the first frame update
    void Start()
    {
	    StartCoroutine(Timeout());
    }

	// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
	void FixedUpdate()
	{
		transform.Translate(0,-moveSpeed,0);
	}
	
	IEnumerator Timeout()
	{
		yield return new WaitForSeconds(timeout);
		Destroy(this.gameObject);
	}
	
}

This will make them fall, but also timeout after 5 seconds so that they don’t pile up.
Of course you can expand on this, but thats the basics