Home > Back-end >  Unity3d too many clones
Unity3d too many clones

Time:01-02

So I m trying to make 10 candies on center of road. Instead 10 its making 77 with the tag. I changed the condition can't fix it still. func is called on update

void CloneCandyCenter() {
     if(GameObject.FindGameObjectsWithTag("r1candycenter").Length  < 2) {
        Debug.Log("0 candies now adding 10 more");
       
        for(int counter = 0; counter < 10; counter  ) {
     Instantiate(R1candyCenter, new Vector3(0,0, CandyZpos.z), transform.rotation, Road1Trans);        
        CandyZpos.z  = 2;
        
        }
    }
}

CodePudding user response:

Dont call CloneCandyCenter in the apdate, as this is being called 60 times per second approx.

Call it in the Start() for example to be called once, or upon key press.

If (Input.GetKeyDown(KeyKode.Space))
    CloneCandyCenter();

However if the R1CandyCenter gamebject has got the tag, in the second call there should be 10 already, so you should only have the first 10, so apart from the inneficiency of GameObject.FindGameObjectsWithTag being called in an update which is not recommended, your code should be working fine regarding the number of abjects created.

I suggest to use a counter:

int candyCenterCounter = 0; //class variable
void CloneCandyCenter() {
     if(candyCenterCounter < 2) { //2 would not make sense if objects are instantiated 10 by 10
        Debug.Log("0 candies now adding 10 more");

     for(int counter = 0; counter < 10; counter  ) {
         Instantiate(R1candyCenter, new Vector3(0,0, CandyZpos.z), 
         transform.rotation, Road1Trans);        
         CandyZpos.z  = 2;
     }
     candyCenterCounter =10 
}
  • Related