Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by thornecreative · Jun 01, 2015 at 01:06 PM · c#unity 2ddestroyspawnbackground

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

Comment
Add comment · Show 7
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SterlingSoftworks · Jun 01, 2015 at 02:52 PM 1
Share

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. :)

avatar image thornecreative · Jun 01, 2015 at 06:33 PM 0
Share

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?

avatar image SterlingSoftworks · Jun 01, 2015 at 06:58 PM 2
Share

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.

avatar image SterlingSoftworks · Jun 03, 2015 at 06:30 PM 1
Share

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!

avatar image neonblitzer · Jun 03, 2015 at 08:29 PM 1
Share

Sorry, @SterlingSoftworks, I ruined your iterative $$anonymous$$ching plan and just gave the code :D

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

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! :)

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SterlingSoftworks · Jun 03, 2015 at 08:43 PM 2
Share

Nooooo you foiled my plans of ultimate learnification!

avatar image thornecreative · Jun 04, 2015 at 06:52 AM 1
Share

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!

avatar image
1

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image thornecreative · Jun 04, 2015 at 08:50 AM 0
Share

Thanks so much, worked like a charm ;)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges