- Home /
Spawning 2D objects randomly and infinitely
Hey guys, I´m pretty new to Unity and I´m trying to create a infinite runner of sorts using the engine 2D tools.
I´m currently having a LOT of headaches regarding spawning objects in my scene, infinitely and randomly.
The basic concept is pretty simple: An infinite 2D runner (where the player is always running to the right), and, as he advances, different types of obstacles appear.
For some reason, the objects have been spawning in only one location and on top of each other, and I can´t figure out how to space them out and solve this problem.
Here follows my Spawn script:
using UnityEngine;
using System.Collections;
public class SpawnScript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f; //spawn aleatoriamente entre 1s
public float spawnMax = 2f; //e 2s
// Use this for initialization
void Start () {
Spawn();
}
void Spawn()
{
Instantiate(obj[Random.Range(0, obj.Length)], transform.position, Quaternion.identity);
Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}
}
Regarding location.... You're instantiating them at the location of the object that has the SpawnScript component. So if that doesn't move, they'll always be in the same place. It's not clear what you're intending here. If you want to put them in specific places, then you need to do that. You could put the location in the instantiate call or you could grab a reference to the object when you instantiate it and set values on its transform.
Answer by Bizzy1994 · Oct 11, 2016 at 10:23 AM
You can just set a public float CooldownTime and a private float LastSpawn and use it in Update() like
if(Time.time >= LastSpawn + CooldownTime)
{
Instantiate(...);
LastSpawn = Time.time;
}
Your answer
Follow this Question
Related Questions
Switch Players during play 2 Answers
2d shooting problem 1 Answer
Having some stuck issues on the 2D infinite runner 0 Answers
Firing Projectiles in the same direction as my character is looking. 1 Answer