• 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 Geta-Ve · Jul 18, 2012 at 07:39 AM · destroytimedistanceinstance

Destroy instances after set time

Heyo! So this is the set up thus far.

http://youtu.be/mJ8NFJcs4Uw

That video, in case you don't want to watch shows one player character dodging towers is he flies through them (or, in the case of the code, as the towers fly by the player).

What I'd like to happen is that the INSTANCES of the tower prefab is destroyed either A) when an appropriate amount of time has passed, or B) when they hit a specific set of coordinates, ie. -50 and -50 on the Z and X axis (or something).

Currently I have the towers being spawned from one tower prefab at random intervals. So I figured, instead of detecting when the towers are past the cameras range and destroying them at that point, I would wait a predetermined amount of time, let's say 10 seconds, and then destroy them. I can then decrease the time limit as the difficulty increases (faster towers).

I, however, am stuck on a good way to destroy the towers. This is not to say that I am unable, I have already set up a solution where a script, attached to the tower prefab itself, runs every 10 seconds destroying said towers. This, however, ended up being very messy, I had no control over determining how many towers had been destroyed.

So, what I have attempted to do is integrate the destroy functionality in to my tower creation script, which is attached to a null/empty object at the center of the scene. And herein lies my issue.

For the life of me I am unable to destroy said towers, with any method that I have found, utilizing Destroy. My current attempt, as you will see below was me simply waiting for 10 seconds and then invoking Destroy on the newTower variable.

I will be honest, I have no clue if that was even SUPPOSED to work, but I tried it anyways. There are other solutions I have attempted but all have yielded no results. For example, amoung many other attempts, I tried GameObject.Find("tower_prefab") within Destroy, but that too was a bust.

So ya, I am at a total loss. It should be noted, that I am, obviously, hugely new to programming/unity, so I could very well be doing something insanely stupid! lol

TowerCreate Script

#pragma strict

var newTower : Rigidbody; var towerSizeX = 1.0; var towerSizeY = 1.0; var towerSizeZ = 1.0; var towerLifeTime = 10.0; //seconds var towerSpawnTimeMin = 0.05; var towerSpawnTimeMax = 0.5;

private var towerDestroyCount = 0; private var towerCreationCount = 0;

function Start () { while(true) { yield new WaitForSeconds(Random.Range(towerSpawnTimeMin,towerSpawnTimeMax)); var towerNum = 1;

     for (var i = 0; i < towerNum; i++)
     {
         var towerSpawnPosition = Instantiate
             (newTower,  
                 Vector3
                 (
                     Random.Range(-100,100),
                     Random.Range(0,0),
                     Random.Range(190,200)
                 ), 
                 Quaternion.identity
             );
         
         newTower.transform.localScale = new Vector3(towerSizeX, towerSizeY, towerSizeZ);            
         
         Debug.Log("Tower created");
         towerCreationCount++;
     }
 }
 
     while(true)
 {
     yield new WaitForSeconds(towerLifeTime);        
     
     newTower.Destroy(gameObject);
     
     Debug.Log("Tower destroyed");
     towerDestroyCount++;
 }    
 

}

Comment
Add comment
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

1 Reply

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

Answer by save · Jul 18, 2012 at 11:30 AM

You would benefit in reusing the objects instead of destroying and instantiating, that way it would also be optimized for mobile devices too. I cooked up a script which handles this:

 #pragma strict
 
 /* Spawn & Reuse Objects
     Updated: 2012-07-18
 */
 
 enum PLAYERAXIS {
     x,y,z
 }
 
 var objectPrefab : GameObject; //The object you wish to spawn
 var playerTransform : Transform; //Player's transform (we use this to set position of the spawn area)
 var totalSpawnObjects : int = 20; //The amount of objects that is allowed in the scene
 var spawnPause : float = .5; //The pause between spawns
 var spawnAreaPosition : Vector3 = new Vector3(0,0,0); //The position of the spawn area
 var spawnAreaSize : Vector3 = new Vector3(100,1,0); //The size of the spawn area (we then randomly spawn inside this area in X, Y and Z)
 var followPlayerOnAxisDistance : PLAYERAXIS = PLAYERAXIS.z; //The axis the spawn area follow the player in distance
 var distanceFromPlayer : float = 20.0; //The distance of the spawn are to the player
  
 private var spawnTimeScheduler : float = .0;
 private var spawnPointer : int = 0;
 
 // Static variables for cached components of the objects below (we use this to access the spawned objects outside the script easily)
 static var objects : GameObject[];
 static var objectsTransform : Transform[];
 static var objectsRenderer : Renderer[];
 
 function Start () {
     objects = new GameObject[totalSpawnObjects];
     objectsTransform = new Transform[totalSpawnObjects];
     objectsRenderer = new Renderer[totalSpawnObjects];
     if (playerTransform==null) playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
 }
 
 function Update () {
     if (Time.time>=spawnTimeScheduler) Spawn();
 }

 function Spawn () {
     //Position the spawn area
     spawnAreaPosition = playerTransform.position;
     switch (followPlayerOnAxisDistance) {
         case PLAYERAXIS.x: spawnAreaPosition.x+=distanceFromPlayer; break;
         case PLAYERAXIS.y: spawnAreaPosition.y+=distanceFromPlayer; break;
         case PLAYERAXIS.z: spawnAreaPosition.z+=distanceFromPlayer; break;
     }
 
     //Bake the spawn position into a variable
     var spawnPosition : Vector3 = Vector3(
         spawnAreaPosition.x-Random.Range(-spawnAreaSize.x/2, spawnAreaSize.x/2),
         spawnAreaPosition.y-Random.Range(-spawnAreaSize.y/2, spawnAreaSize.y/2),
         spawnAreaPosition.z-Random.Range(-spawnAreaSize.z/2, spawnAreaSize.z/2)
     );
 
     //Spawn new object
     if (objects[spawnPointer]!=null) {
         //Reuse the object
         objectsTransform[spawnPointer].position = spawnPosition;
     } else {
         //Instantiate the object
         var thisObject : GameObject = Instantiate(objectPrefab, spawnPosition, Quaternion.identity);
         CurrentSpawnedComponentCache(spawnPointer, thisObject.gameObject, thisObject.transform, thisObject.renderer);
     }
     if (spawnPointer++>=totalSpawnObjects-1) spawnPointer = 0;
     spawnTimeScheduler = Time.time+spawnPause;
 }
 
 //Cache the components of spawned objects
 function CurrentSpawnedComponentCache (i : int, g : GameObject, t : Transform, r : Renderer) {
     objects[i] = g;
     objectsTransform[i] = t;
     objectsRenderer[i] = r;
 }
 
 //Draw the spawn area in Scene view
 function OnDrawGizmos () {
     Gizmos.color = Color.yellow;
     Gizmos.DrawWireCube (spawnAreaPosition, spawnAreaSize);
 }

Here's an example scene as UnityPackage. Feel free to ask if there's something in the script that seems unclear.

Comment
Add comment · Show 15 · 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 save · Jul 18, 2012 at 11:40 AM 0
Share

Remember to type your variables too, I notice you haven't done that in the script you posted. Just as a re$$anonymous$$der for faster performance! :-)

Regarding the example: You could also have a script on the objects which moves them towards the player ins$$anonymous$$d if you want a continuously endless game session.

avatar image Geta-Ve · Jul 18, 2012 at 11:35 PM 0
Share

Hey save! Thank you so much for your answer! I will be trying it out tonight, I just wanted to thank you in advance. I will have to study your script intently. :)

avatar image save · Jul 18, 2012 at 11:44 PM 0
Share

Awesome! Hope you don't feel like your previous work is for nothing, the way you did it is ok but not suitable for low-end devices. If you have repeating objects which travel out of scene view there's a good chance a reuse cycle is the best way to go.

Check back with questions if they come up!

avatar image Geta-Ve · Jul 19, 2012 at 12:02 AM 0
Share

Furthermore, I just tried out the script as is, all I have to say is WOW, so much control. I definitely need to study this.

Thank you so much!!

EDIT: Also, no I don't feel I wasted my time with the previous script, I had learnt a lot piecing it together. and I think I am going to learn even more dissecting your script and seeing what makes it tick. :)

avatar image Geta-Ve · Jul 19, 2012 at 12:14 AM 0
Share

Actually, I guess I do have one question, off the top of my head. You mentioned that I should define the types for my variables, though I was under the impression that, at least in JavaScript, it wasn't really all that important, as JS detects automatically?

A moment of thought would tell me that defining the variable type would simply give the game one less thing to calculate, thus speeding things up.

Would I be correct in this assumption? :)

Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

6 People are following this question.

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

Related Questions

Destroy A Game Object After Mouse is held for a certain amount of time 1 Answer

destroying instructions sequence 1 Answer

how to destroy an instance of multiple prefabs 2 Answers

change instance color based on distance from player 0 Answers

create a destroyer for 2d infinite runner game objects. 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