How to Destroy spawn objects after an time Interval

Hi Everyone,

I got stuck in spawning, I am newbie to javascript I had managed to create random spawning of multiple objects but the frame rate is too low in android devices.I dono how to clear the objects spawned and unused in the game which is running in background.Please help me to find out how to destroy spawn objects in certain interval of time.

You could use this:

this.scheduleOnce(function () {
    theNodeYouWantToDestroy.destroy();
}, 1.5); // 1.5 second
1 Like

Hi jejeman,

Thanks for your response!!!

This is my code used for spawning multiple objects , can please check it out it is the correct way to call spawning of objects

cc.Class({
    extends: cc.Component,

    properties: {
        rocketPrefab1: {
            default: [],
            type: cc.Prefab
        },
        
    },

    // use this for initialization
    onLoad: function () {
       
       this.spawnRoc();
       this.timer =0;
    },

    // called every frame, uncomment this function to activate update callback
     update: function (dt) {

       this.timer += dt;

        if(this.timer > 0.5){
          this.spawnRoc();
          this.timer =0;
          
       }
      
      
},
     
     spawnRoc : function(){
    
         
         for (let i = 0 ; i <this.rocketPrefab1.length; i++){
         
         let rocspa = cc.instantiate(this.rocketPrefab1[Math.floor(this.rocketPrefab1.length * Math.random())]);
         this.node.addChild(rocspa);
         rocspa.setPosition(0,0);
       
       
        this.scheduleOnce(function () {
            rocspa.destroy();
             
         }, 0.5); 
    }
}

});

Thanks,

That should work although I would not put that in the update. I’m not sure about performance but its an IF that will be evaluated many time by seconds.

You could also use this.schedule to spawn your object

http://cocos2d-x.org/docs/api-ref/creator/v1.5/classes/Animation.html#method_schedule

You can use a Sequence with a DelayTime action and a RemoveSelf action.

Thanks for your response!!!

Can you provide me some reference because i am new to javascript

Thanks,

Something like:

var delay = cc.delayTime(seconds);
var remove = cc.removeSelf();
var sequence = cc.sequence(delay, remove);
sprite.runAction(sequence);
1 Like

don’t worry for
Timer see :
https://github.com/cocos-creator/creator-docs/blob/master/source/en/scripting/scheduler.md
and for
Controlling and manipulation of spawn objects see:
https://github.com/cocos-creator/creator-docs/blob/master/source/en/scripting/pooling.md