Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.mkv25.util;
- import nme.display.DisplayObject;
- import nme.display.Sprite;
- /**
- * Recycles stage assets by creating and managing display assets, and cleanly removing from them from the stage ready for reuse.
- * @author John Beech
- */
- class Recycler<T>
- {
- public var classType:Class<T>;
- public var artworkProperty:String;
- public var params:Array<Dynamic>;
- private var itemsInUse:Array<T>;
- private var recycledItems:Array<T>;
- private var artBin:Sprite;
- /**
- * Define a recycler for type T, specifying artwork and additional params for construction.
- * @param artworkProperty
- * @param params
- */
- public function new(classType:Class<T>, artworkProperty:String = "", params:Array<Dynamic> = null) {
- this.classType = classType;
- this.artworkProperty = artworkProperty;
- this.params = params;
- itemsInUse = new Array();
- recycledItems = new Array();
- artBin = new Sprite();
- }
- /**
- * Constructs an item of type T, or recycles an existing item of type T.
- * @return an item of type T
- */
- public function getItem():T {
- var item:T;
- if(recycledItems.length > 0) {
- item = recycledItems.pop();
- }
- else {
- if(params == null) {
- item = Type.createInstance(classType, params);
- }
- else {
- item = Type.createInstance(classType, null);
- }
- }
- itemsInUse.push(item);
- return item;
- }
- /**
- * Recycle all items of type T tracked by this recycler and remove them or their art assets from the stage.
- */
- public function recycleAll():Void {
- var item:T;
- var artwork:DisplayObject;
- while(itemsInUse.length > 0) {
- // Remove item from usage
- item = itemsInUse.pop();
- // Attempt to remove artwork from stage
- if (artworkProperty != "") {
- if (Reflect.hasField(item, artworkProperty)) {
- artwork = Reflect.field(item, artworkProperty);
- artBin.addChild(artwork);
- }
- else {
- var fields:Array<String> = Type.getInstanceFields(classType);
- if (arrayContains(fields, artworkProperty)) {
- artwork = Reflect.field(item, artworkProperty);
- artBin.addChild(artwork);
- }
- else {
- throw ("Recycled item (" + item + ") does not have an valid art reference (" + artworkProperty +")");
- }
- }
- }
- else if (Std.is(item, DisplayObject)) {
- artBin.addChild(cast item);
- }
- // Recycle item
- recycledItems.push(item);
- }
- }
- private function arrayContains(array:Array<String>, needle:String):Bool {
- for (item in array) {
- if (item == needle) {
- return true;
- }
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment