Create random falling objects in unity C#

2.4k Views Asked by At

i am starting to learn unity3d and am developing a 2d game but need some help at the main menu. I have a coin texture which i would like to spawn multiple times above the screen and fall down to create a falling coin texture. Spawn points should be random and entities should be destroyed after falling off the screen, but i have no idea how to do it. Any help will be greatly appreciated. Thank you

Image Upload: https://i.stack.imgur.com/m1rXM.jpg

3

There are 3 best solutions below

0
On

I will give you some starting points to done your task. You can read about`

  1. RigidBody(RigidBody2D)
  2. Collider(Collider2D)
  3. MonoBehaviour Callbacks for example OnTriggerEnter(OnTriggerEnter2D) or OnCollisionEnter(OnCollisionEnter2D)
  4. For randomness you can read about Random class and his methods like Random.randomInsideUnitCircle.
0
On

If I were you I'd start by reading up on Unity's particle system. By setting up some parameters in the editor it can exactly do what you want and very efficiently as well.

Some important parameters to consider:

  1. Emitter shape: You want this to be a rectangle in your case, positioned at the top of the scene.
  2. Initial velocity: You want this to be something like (0,-2,0) for downwards falling coins.
  3. Emission rate: Determines how fast new coins will be produced.
  4. Particle shape: Either a coin texture or a coin mesh or whatever you want.
  5. Starting lifetime: The duration of each coin. The coin will be properly destroyed after this time.

The particle system will automatically choose random points within the emitter shape.

0
On

Create a coin prefab with rigidbody2d and a collider component. Create an empty game object, name it something like Spawner, and add the script bellow to it. (I named it Spawner)

  public class Spawner : MonoBehaviour
{
[SerializeField] GameObject coinPrefab;
private float minX = -10, maxX = 10; // change it
private float timeMin = 1, timeMax = 5; // change it
void Start()
{
    Invoke("SpawnCoins", Random.Range(timeMin, timeMax));
}
void SpawnCoins()
{
    float randPosx = Random.Range(minX, maxX);
    coinPrefab = Instantiate(coinPrefab, new Vector2(randPosx, transform.position.y), Quaternion.identity);
    Invoke("SpawnCoins", Random.Range(timeMin, timeMax));
}

}

I recommend you search what each function does. Check Unity manual. To destroy the coins after hitting ground try use OnCollisionEnter or OnTriggerEnter function.

Also after being confident with the above, check object pooling.