- Home /
Destroy instances after set time
Heyo! So this is the set up thus far.
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++;
}
}
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.
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.
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. :)
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!
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. :)
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? :)
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Time a ball is thrown in the air? 2 Answers
Rocket to disappear after a few seconds? 2 Answers
destroying a gameobject clone 2 Answers
Destroy an instance of a prefab 1 Answer