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

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.