-
-
Save pjburnhill/44fc352ea79275445909c4b96df34bac to your computer and use it in GitHub Desktop.
To optimize object cloning on scenes, this plugin can be helpful.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var ObjectPool = pc.createScript('objectPool'); | |
| ObjectPool.attributes.add('maxCount', { type : 'number', default : 1 }); | |
| ObjectPool.attributes.add('sleepTime', { type : 'number', default : 0 }); | |
| ObjectPool.prototype.initialize = function() { | |
| this.entity.enabled = false; | |
| this.index = 0; | |
| this.objects = []; | |
| this.createClones(); | |
| this.app.on('ObjectPool:' + this.entity.name, this.onClone, this); | |
| this.app.on( | |
| 'ObjectPool:' + this.entity.name + '@Clear', | |
| this.onClear, | |
| this | |
| ); | |
| }; | |
| ObjectPool.prototype.onClear = function() { | |
| for(var index in this.objects){ | |
| var object = this.objects[index]; | |
| object.enabled = false; | |
| } | |
| }; | |
| ObjectPool.prototype.createClones = function() { | |
| for( var i = 0; i < this.maxCount; i++ ){ | |
| var object = this.entity.clone(); | |
| object.script.destroy('objectPool'); | |
| object.enabled = false; | |
| this.objects.push(object); | |
| } | |
| this.entity.destroy(); | |
| }; | |
| ObjectPool.prototype.onClone = function(callback) { | |
| var object = this.objects[this.index]; | |
| if(object){ | |
| object.enabled = true; | |
| if(callback){ | |
| callback(object); | |
| } | |
| if(this.sleepTime > 0){ | |
| clearTimeout(object.timer); | |
| object.timer = setTimeout(function(object){ | |
| object.enabled = false; | |
| }, this.sleepTime * 1000, object); | |
| } | |
| } | |
| this.index++; | |
| if(this.index > this.objects.length - 1){ | |
| this.index = 0; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment