销毁Phaser中的精灵(Sprite)

18

我在Phaser中销毁Sprites时遇到了问题。

我有一个JavaScript对象,叫做Block。Block具有Sprite属性,可以像下面这样设置:

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

在我的代码的某个点上,Block 被两个不同的数组引用:

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

在某个Update()周期中,我需要销毁精灵,因此我使用以下代码:

square[0].sprite.destroy(true); //Destroy the sprite.
square[0] = null; //Remove the reference.
在下一次 Update() 循环中,当我查看 destroy[0] 时,我希望看到的是:
destroy[0].sprite: null

然而我正在看到的是:

destroy[0].sprite: b.Sprite

使用刚刚默认设置为false的属性,我担心如果我现在将destroy [0]设置为null,那个精灵对象会发生什么?

它会漂浮还是会自动清理? 我应该以某种方式首先销毁Block对象吗? 此外,如果destroy()不会使引用为空,则它与kill()有何不同?

对此的任何想法都将不胜感激。


2
如果没有引用它,垃圾收集器会清理它。 - Oriol
如果您已经找到了您要寻找的内容,请接受一个答案。 - James L.
2个回答

22

杀死和销毁的区别

kill意味着停止渲染,但对象仍然存在。如果你想创建可重复使用的对象,这是很好的选择。 您可以重新创建该对象,而无需实际再次创建该对象的成本。

destroy应该删除对象以及与之相关的所有内容。当你想将对象发送到垃圾收集器时使用它。

请注意,对于一些像文本这样的对象,您不能使用kill,只能使用destroy

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


4

@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 destroy方法仅从对象中删除Phaser特定属性。JS负责通用对象垃圾收集。该对象之所以逃脱,是因为您在作用域中仍然有有效的引用。
通过从作用域中删除引用destroy[0].sprite = null或等待下一个状态更改作用域(假设destroy不是静态变量)来解决此问题。您不必自己管理内存资源,JS!= C。只需确保不要跨不同作用域泄漏变量。 什么是JavaScript垃圾回收?(尽管我认为不再推荐使用delete命令进行GC,但在Phaser中肯定不是必需的)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接