作为场景对象的基础,我有一个根 Object3D。我的数据从这个根加载为 Object3D 的树结构。使用 BufferGeometry/MeshPhongMaterial 将网格添加到叶 Object3D。我通过将根 Object3D 传递到此方法来清除现有树:
clearScene:
function (obj) {
if (obj instanceof THREE.Mesh)
{
obj.geometry.dispose();
obj.geometry = undefined;
obj.material.dispose();
obj.material = undefined;
obj = undefined;
}
else
{
if (obj.children !== undefined) {
while (obj.children.length > 0) {
this.clearScene(obj.children[0]); // removing children changes the length of the array.
obj.remove(obj.children[0]);
}
}
}
}
考虑下面的简单树:
- 场景(场景)
- 根 (Object3D)
- 分支 (Object3D)
- 叶子(网状)
- 分支 (Object3D)
- 根 (Object3D)
一旦这个结构出现在场景中,我就会观察堆(使用 Chrome 的开发工具)。我可以看到 3 个 Object3Ds 对象和 2 个 Mesh 对象(额外的是原型(prototype))。
当我调用 clearScene(Root) 时,我看到它一步步穿过树,移除 Object3D,并清理网格。但是,当我观察堆时,我发现尽管 Object3D 已被移除,但 2 个 Mesh 对象(及其关联的 BufferGoemetry 和 Material 对象)仍然存在。如果我在清除后第二次加载数据,我会看到 3 个 Object3D(好的)和 4 个网格(不好的)。
我相信这意味着引用没有被正确清除,但我没有看到堆中有任何保留器可以执行此操作。
我一定是遗漏了其他导致这些对象徘徊的东西。
r69dev(我在 r68 中看到了同样的东西),在 Chrome 36.0.1985.125 中测试
最佳答案
在github上提交的问题(关注):https://github.com/mrdoob/three.js/issues/5175
r69dev 需要显式调用网格的 dispose 方法以正确删除渲染器持有的引用。
工作代码:
clearScene:
function (obj) {
if (obj instanceof THREE.Mesh)
{
obj.geometry.dispose();
obj.geometry = null;
obj.material.dispose();
obj.material = null;
obj.dispose(); // required in r69dev to remove references from the renderer.
obj = null;
}
else
{
if (obj.children !== undefined) {
while (obj.children.length > 0) {
this.clearScene(obj.children[0]);
obj.remove(obj.children[0]);
}
}
}
}
关于javascript - 取消分配 BufferGeometry?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126352/