- Home /
instantiate object infinitely
I have a script that instantiates an object infinitely every second. How come every so often there is a little click?
#pragma strict
var speed : int = 2;
var chrismasBall : GameObject; //GameObject
var instanza:GameObject[]; //instanza
//var texBall : Texture[] = new Texture [5]; //Array di texture
var score : int = 0;
function Start () {
StartCoroutine(Creation(1)); //Coroutine
}
function Update () {
//Physics.gravity = Vector3(0, -0.05, 0); // aggiungo gravità
/*if(instanza==null){
print("cancello");
}
*/
}
function Creation(tempo){
while(true){ //finchè è vero esegui il ciclo
var posizione : Vector3 = Vector3 (Random.Range(-1.9,1.9),2.5,2);
var pallaNuova : int = Random.Range(0,instanza.length-1);
Instantiate (instanza[pallaNuova], transform.position+posizione, Random.rotation); //instanza chrismasBall
//instanza.AddComponent(Rigidbody); //aggiungo rigidbody alle instanze
/*
instanza.transform.position.x = Random.Range(2,-2); //raggio di instanza
instanza.transform.position.y = 2;
instanza.transform.position.z = 0.2; //distanza dalla Main Camera
instanza.transform.Translate(0, Time.deltaTime, 0);
*/
yield WaitForSeconds(tempo);
}
}
When instantiates the object stops for a few moments, the game slowing down
why would u want to instantiate infinitely? Ofcourse the game will slow down with soo many objects... At least destroy some objects or something?
As others have commented, this is not a good idea. If you keep making game objects, you will eventually run out of memory and crash. You are likely going to want to implement some sort of object pooling solution (where you only use a smaller pool of actual objects to simulate a ton of objects). As you are instantiating new objects, you pull from the pool (assu$$anonymous$$g that you don't need some of the old objects anymore and can free them up). Here is something to get you started: Forum thread on object pooling script
Your answer
![](https://koobas.hobune.stream/wayback/20220613103905im_/https://answers.unity.com/themes/thub/images/avi.jpg)