2014-07-05 113 views
14

我在Phaser中摧毀精靈時遇到了麻煩。在Phaser中摧毀精靈

我有一個JavaScript對象,我們稱它爲Block。塊有一個精靈屬性時設置像這樣:

this.sprite = this.game.add.sprite(this.x, this.y, 'blocks', this.color); 

在我的代碼中的某一點,塊是由兩個不同的數組引用:

square[0] = Block; 
destroy[0] = Block; 

在一定的更新()循環,我需要消滅精靈,所以我用下面的代碼:

square[0].sprite.destroy(true); //Destroy the sprite. 
square[0] = null; //Remove the reference. 

在下次更新()循環,當我看着破壞[0],我希望看到:

destroy[0].sprite: null 

但是我所看到的是:

destroy[0].sprite: b.Sprite 

只需默認設置爲false屬性。我擔心的是,如果現在將destroy [0]設置爲null,那麼這個精靈對象會發生什麼?

它只是浮動或自動清理? 我應該首先以某種方式銷燬Block對象嗎? 另外,如果destroy()不是null的引用,它與kill()有什麼不同?

關於此事的任何想法將不勝感激。壓井之間

+2

垃圾收集器將它清理乾淨,如果有它沒有提及。 – Oriol

+0

如果你找到了你要找的東西,請接受答案。 –

回答

19

差異銷燬

Kill應該停止渲染,但對象仍然存在。如果你想製作一個可重用的對象,這很好。 您可以再次創建對象,而無需再次實際創建對象。

Destroy應該刪除對象和與之相關的所有東西。當你想把對象發送到垃圾回收器時,你可以使用它。

請注意,如文本的某些對象,則不能使用kill,你只能使用destroy

參考: http://www.html5gamedevs.com/topic/1721-how-to-remove-text/#entry12347

+0

如何操作垃圾回收器的對象? –

0

@ibnu是正確的。 Destroy核武器對象,而kill停止渲染。但是,您的問題涉及內存泄漏和GC。我不是GC專業人員,但這是我認爲正在發生的事情。

//create an object 
this.sprite = this.game.add.sprite(this.x, this.y, 'blocks', this.color); 
//create additional references to the object 
square[0] = Block; 
destroy[0] = Block; 
//destroy the object via Phaser's call. Remove 1/2 reference 
square[0].sprite.destroy(true); //Destroy the sprite. 
square[0] = null; //Remove the reference. 

destroy[0].sprite仍然持有對您的「被銷燬」精靈的引用。 this.sprite可能也是。這是因爲Phaser銷燬方法僅從對象中刪除Phaser特定屬性。 JS is in charge of generic object Garbage Collection。該對象正在逃避,因爲您在範圍內仍然有有效的引用。

通過從範圍destroy[0].sprite = null中刪除引用或等待下一個狀態更改範圍(假設destroy不是靜態var)來解決此問題。你不必管理自己的內存資源,JS!= C。只要確保你在變量範圍內不需要變量leak

What is JavaScript garbage collection?(雖然我不認爲建議的delete命令GC做了,它肯定不是在移相器需要)