# give a prefab clones a script from another prefab in Unity3d

I have the following :

TurretBallmanager :

using UnityEngine;
using System.Collections;

public class TurretBallManager : MonoBehaviour {

// Use this for initialization
public GameObject BallPrefab;
public GameObject TurretPrefab;
public static TurretBallManager instance;
public int turretSpawnTime=35;
public int LastTurretTime=0;
Vector2 v;
void Start () {
instance = this;
v = new Vector2(TurretPrefab.transform.position.x,TurretPrefab.transform.position.y);
}

// Update is called once per frame
void Update () {
if (Time.time > LastTurretTime + turretSpawnTime) {
GameObject T = Instantiate(TurretPrefab,v,Quaternion.identity) as GameObject;
v.x=T.transform.position.x+2;
}
}
}


Turret class :

using UnityEngine;
using System.Collections;

public class Turret : MonoBehaviour {

// Use this for initialization
double LastBallTime=0.0;
double LastTurretTime=0.0;
public decimal spawnballTime=1.5;
Vector2 v ;
void Start () {

}

// Update is called once per frame
void Update () {
if (Time.time > LastBallTime + spawnballTime) {
LastBallTime=Time.time;
Debug.Log (transform.position);
GameObject B = Instantiate(TurretBallManager.instance.BallPrefab, transform.position, transform.rotation) as GameObject;
}

}
}


Ball class :

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

// Use this for initialization
void Start () {

}
void OnMouseDown() {
Object.Destroy (gameObject);
}
// Update is called once per frame
void Update () {

}

void OnBecameInvisible ()
{
Debug.Log ("destroyed");
Destroy(gameObject);
}
}


I have a turret wish fire a ball every 1 sec ,the ball is a prefab wish have the Ball class ( when the ball is out of bounds or is touched it should be destroyed ) what i'm trying to do is creating a another turret every 35 sec wish also should fire a ball every 1 sec .. what i am facing is the fallowing problem :

1. the turret is being created after 35 sec but it's ball are not implementing the ball script and they are not being destroyed
2. An overflow is occurring due to the number of balls created and the whole project is freezing

• Image 1 : as soon as the game begin
• Image 2 : When 35 seconds ends
• Image 3 : you can see that millions of turrets are created at the same time as soon as 35 sec ends

The turretballmanager is a class given for the Maincamera

// Update is called once per frame

Your timer is never being reset. This means that after the soon as your spawning condition is satisfied: if (Time.time > LastTurretTime + turretSpawnTime), your program will continue to spawn turrets every time Update() is called. You appear to have a better approach in your ball spawner.

You could update the LastTurretTime like so:

 if (Time.time > LastTurretTime + turretSpawnTime) {
LastTurretTime = Time.time;
GameObject T = Instantiate(TurretPrefab,v,Quaternion.identity) as GameObject;