Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 SalvadorKinnes · Jul 02, 2019 at 07:33 PM · spawningdestroygameobject

How do I stop spawning prefabs after a certain amount of time? Also how do i detroy the cloned prefabs created to imporve the performance.

Can someone please help me? Im new to c# and have been folling tutorials mainly, it would be a big help if someone could assist me please. This is my code

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class RandomSpawn : MonoBehaviour {
 
     // prefabs to instantiate
     public GameObject prefab1, prefab2;
 
     // spawn prefabs once per 2 seconds
     public float spawnRate = 2f;
 
     // variable to set next spawn
     float nextSpawn = 0f;
 
     // varaible to contain random value
     int whatToSpawn;
 
     
         // Update is called once per frame
     void Update() {
         if (Time.time > nextSpawn)
         { // if time has come
             whatToSpawn = Random.Range(1, 3); // define random value between 1 and 5 (6 is exclusive)
             Debug.Log(whatToSpawn);
                         
 
             // instantiate a prefab depending on random value
             switch (whatToSpawn)
             {
                 case 1:
                     Instantiate(prefab1, transform.position, Quaternion.identity);
                     break;
                 case 2:
                     Instantiate(prefab2, transform.position, Quaternion.identity);
                     break;           
             }
 
                      
            
             //set next spawn time
             nextSpawn = Time.time + spawnRate;
         }  
         
     }
 } 
 
 
Comment
Add comment · Show 2
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 ShadoX · Jul 03, 2019 at 04:02 PM 0
Share

Sorry for not providing specific code, but to comment on your question: 1) You already use Time.time to check for when to Spawn the next thing, so all you would really need to do is to add another variable that specifies for how long this should keep going on.

A simple example would be:

 float spawnObjectsForSeconds = 10f;
 float timeToStopSpawningObjects;
 void Start() {
    timeToStopSpawningObjects = Time.time + spawnObjectsForSeconds;
 }

and then in the update method change:

 if (Time.time > nextSpawn)

to

 if (Time.time > nextSpawn && Time.time < timeToStopSpawningObjects )

What this basically does is that it you store a specific time in the future, after which the IF check above ^ will stop running. Or basically Time.time will have a larger value than timeToStopSpawningObjects which consists of the time the script started running + 10 seconds (spawnObjectsForSeconds )

Of course there are other ways of doing this, but this should be fairly simple.

As for Destroying objects and keeping a good performance. I would suggest that you look into Object Pools for this :)

Normally you don't want to keep Instantiating and Destroying objects all the time as it's a bit resource intensive for the PC, or might slow down things in the long run. What a lot of games do is to use a "pool of objects", which you could basically compare to a list or array that already has a set amount of the Objects that you want to use. So ins$$anonymous$$d of Instantiating and Destroying objects when needed, you take a object from this pool, use it when you need it, then stop using it and return it to the pool, without destroying it.

Basically you always have those objects in the game, but you don't always use them. Of course it depends on your game. If you plan on doing a lot of Instantiating and Destroying, then I'd suggest to look into a object pool, but if you only do it every now and then, then it should be ok to do.

Could try checking - https://learn.unity.com/tutorial/object-pooling# - https://www.raywenderlich.com/847-object-pooling-in-unity

avatar image SalvadorKinnes ShadoX · Jul 03, 2019 at 06:12 PM 0
Share

Thanks you so much !! This was a real help to me. Have a good day further :)

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by galalhassan · Jul 03, 2019 at 02:50 AM

Use this code to better control the spawning.

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class RandomSpawn : MonoBehaviour {
  
      // prefabs to instantiate
      public GameObject prefab1, prefab2;
  
      // spawn prefabs once per 2 seconds
      public float spawnRate = 2f;
  
      // variable to stop spawning after spawning a certain number
      int stopAfterSpawns = 5;
      
      // variable to stop spawning after a few seconds
      float stopAfterSeconds = 10;
 
      // varaible to contain random value
      int whatToSpawn;
  
      float startingTime = 0f;
 
      void Start(){
           InvokeRepeating("SpawnObject", spawnRate, spawnRate);
           startingTime = Time.time;
      }
 
      void SpawnObject(){
              if (stopAfterSpawns <= 0 || stopAfterSeconds > Time.time - startingTime){
                     CancelInvoke("SpawnObject");
                     return;
              }
              
              stopAfterSpawns = stopAfterSpawns - 1;
 
              whatToSpawn = Random.Range(1, 3); // define random value between 1 and 5 (6 is exclusive)
              Debug.Log(whatToSpawn);
 
 
              // instantiate a prefab depending on random value
              switch (whatToSpawn)
              {
                  case 1:
                      Instantiate(prefab1, transform.position, Quaternion.identity);
                      break;
                  case 2:
                      Instantiate(prefab2, transform.position, Quaternion.identity);
                      break;           
              }
      }
  } 

Now, to destroy the instantiated objects, I would suggest that you create another script and have it attached to the game object you are instantiating. This script would basically have some logic to destroy the game object. So for example if you want to destroy the instantiated clones after they get instantiated by 5 seconds. Invoke a function to run after 5 seconds that destroys the object.

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 SalvadorKinnes · Jul 03, 2019 at 10:04 AM 0
Share

Hi, thank you so much for your help. However i replaced my code with yours and the only problem is that the prefabs are no being spawned. Im not sure why or if they are being spawned but they are not visible if they are being spawned. But thank you so much, I will try to see if i can figure it out. Do you prefabs know why this is happening ?

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

109 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Spawning infinite coins 1 Answer

Why does instantiating a prefab break the original's behaviour 2 Answers

How to only destroy the object the i am in. 3 Answers

Space Shooter: How can I spawn the asteroids more than once? 3 Answers

max amount of enemy present? 2 Answers


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