- Home /
How can i destroy cubes that is randomly generated when i have passed them?
Hello. I am making a game where you have to steer between randomly generated cubes. I noticed that if you play for a long time it get's laggy because of all the cube clones. This is my code for the spawning:
using UnityEngine;
using System.Collections;
public class CubeSpawner : MonoBehaviour {
public GameObject cubePrefab;
public float delayBetweenSpawns = 0.75f;
private float spawnTime;
public float spawnDistance = 105;
public Transform character;
void Awake () {
for ( int i = 0; i < 10; i++ ){
CreateCube ( character.position.z + 10 * i + 10 );
}
gameObject.SetActive ( false );
}
// Use this for initialization
void Start () {
spawnTime = Time.time;
}
void CreateCube ( float pos ){
Instantiate ( cubePrefab, new Vector3 ( Random.Range ( -4.5f, 4.5f ), 0.5f, pos ), Quaternion.identity );
}
// Update is called once per frame
void Update () {
if ( spawnTime < Time.time ) {
CreateCube ( spawnDistance + character.position.z );
spawnTime += delayBetweenSpawns;
if ( delayBetweenSpawns > 0.25f){
delayBetweenSpawns -= 0.002f;
}
}
}
I want it so these cubes get's destroyed when i am 20 yards away from them. (On the z coord) Thanks for taking your time to be reading this!
Cheers
Answer by robertbu · Jun 19, 2013 at 07:20 AM
In a script attached to the cubes, you can do something like this:
var goPlayer : GameObject;
function Start() {
goPlayer = GameObject.Find("Player");
}
function Update() {
if (player.transform.position.z - transform.position.z > 20)
Destory(gameObject);
}
Note from a performance standpoint, you would be better off doing a pooling system where you reuse blocks rather than Instantiating and Destroying them.
Thank you very much for your answer! With this pooling system, can the placement of the reused blocks still be random?
Yes they can still be random. Ins$$anonymous$$d of creating a new block, you just set a new position for an existing block. There are a number of posts on pooling systems.
Thank you once again. For now the script you posted will help me a lot, but i will look into a pooling system later :-)
Your answer
Follow this Question
Related Questions
Changing Color Based on Z position 2 Answers
Why isn't this script working? (Beginner in coding) 2 Answers
Cant Destroy specific object 2 Answers