- Home /
Help with Spawning & Destroying Background Objects in 2D
Hey guys;
I'm putting together a 2D endless runner in my spare time and have been learning for days on how to code using c# - I'm in the process of putting together the background items and I'm trying to get random items like buildings, houses and trees to spawn randomly, then destroy themselves after they're off screen. Can someone please help with a simple code to attach to my building, house and tree prefabs?
Thanks so much in advance for any help/input
There's a lot of ways to do this.. The simplest way I can think of would be to set up a box collider a fair distance from the gameplay screen and just destroy the objects when they hit the box. :)
Thanks for that, sounds like an obvious solution - I just needed someone else to point it out! Being new to writing C# code I spent the better part of 3 hours writing a code only to find out it didn't work! But good learning curve - thanks again, I'll give it a go!
Would you suggest creating an empty game object as a parent then adding all of my background items (trees, buildings, houses) as children? I would imagine I need a script that generates random instances of each child in random order?
Well, again, like I said above there are many ways to achieve one thing. Unity, as compared to just straight scripting, makes our lives as programmers/game developers $$anonymous$$UCH easier.
First, you don't need to set up a parent object or anything like that for the objects spawning. You can do that in your working scene to make your hierarchy look better if you'd like so you don't have a huge list of tree, tree, building, house, tree, etc.
Second, the next thing you should do is set up a BackgroundSpawning script that's sole purpose is to handle the spawning of the background.
Then you'll need to set up a public GameObject[] background; array. (Putting public allows it to be seen in the inspector)
In the inspector, where the new script is at you'll have an array that you can put in a value of how large you want it. In your case, 3. Then you drop your PREFABS of the background objects into the slots.
That will get you started. For the random spawning, do you have any experience using Random.Range? If so, try fiddling with that and Instantiate and see what you can come up with.
Well, post the code that you've got so far (be sure to use the "Code Sample" button to make it look correct!) and we'll see where we can go from there!
Sorry, @SterlingSoftworks, I ruined your iterative $$anonymous$$ching plan and just gave the code :D
Answer by neonblitzer · Jun 03, 2015 at 08:01 PM
Expanding upon SterlingSoftworks' tips :)
The spawner script should have a public array for the spawnable prefabs:
public GameObject[] toSpawn;
And adjustable minimum and maximum time intervals for spawning a thing:
public float minInterval = 1f, maxInterval = 2f;
And a float to keep track of spawn time:
float _nextSpawnTime = 0f;
Also, a reference to a Transform that is a bit outside the screen for the spawn location:
public Transform spawnLocation;
Then, in Update, do something like this:
public void Update() {
// has enough time passed since last spawn?
if (Time.time >= _nextSpawnTime) {
// delay the next spawn time by a random amount
_nextSpawnTime += Random.Range(minInterval, maxInterval);
// select and instantiate a random prefab
int randomIndex = Random.Range(0, toSpawn.Length);
Instantiate(toSpawn[randomIndex], spawnLocation.position, Quaternion.identity);
}
}
The background items should have their own scripts for moving. Here's a very simple one:
public class BackgroundItemMover : MonoBehaviour {
public float speed = 5f;
public void Update() {
transform.position += Vector3.left * speed * Time.deltaTime;
}
}
And the destroyer object on the left side of the screen should have a box collider with the Is Trigger checkbox set, and a rigidbody attached. Use the OnTriggerEnter(Collider other)
callback and the Destroy
method in the script, and you should be all set! You'll get to write this one by yourself ;) And make sure that the background items have a collider, otherwise the destroyer will miss them.
If you want to be all fancy and optimized, you could actually have a pool of, say, 10 GameObjects of each background item that you instantiate at the start of a scene, store in an array and disable right away. Then, select one of those pooled objects at runtime to enable and move to correct position, and when they exit the screen, instead of destroying just disable them and put them back in the pool to wait for being selected again. This is a lot lighter on the CPU if you have very many things happening at once, though a bit unnecessary for now, I think. The first thing you want to do is to make it work at all! :)
Nooooo you foiled my plans of ultimate learnification!
Wow. Amazing - it worked P E R F E C T L Y! Thank you so much, to you both really for taking the time to help a guy out. You have no idea how many hours logged/videos watched/documents read/coffee consumed it's taken to get here. And I'm sure what I'm asking must seem so simple to you lol. $$anonymous$$uch respect, thanks again!
Answer by MitchWardle180 · Jun 04, 2015 at 08:08 AM
TRY THIS
the code hasn't been tested as im at work but it should work
float lifetime = 10f;
float timer;
void Update(){
timer += Time.deltaTime;
if(timer >= lifetime)
Destroy(gameObject);
}
the lifetime variable is how long the building will be alive before it is destroyed and the timer keeps track of how much time has elapsed since the start of the script.
Your answer
Follow this Question
Related Questions
Enemy Spawner help 1 Answer
spawn 3 object in a row at the same time ( unity ) 1 Answer
Multiple Cars not working 1 Answer
Spawning game Object after a period of time 2 Answers
Delete object only when a certain cursor is enabled 1 Answer