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