创建和销毁节点

创建新节点

除了通过场景编辑器创建节点外,我们也可以在脚本中动态创建节点。通过 new Node() 并将它加入到场景中,可以实现整个创建过程。

以下是一个简单的例子:

  1. import { _decorator, Component, Node } from "cc";
  2. const { ccclass, property } = _decorator;
  3. @ccclass("test")
  4. export class test extends Component {
  5. start(){
  6. let node =new Node('box');
  7. node.setPosition(0,0,-10);
  8. }
  9. }

克隆已有节点

有时我们希望动态的克隆场景中的已有节点,我们可以通过 instantiate 方法完成。使用方法如下:

  1. import { _decorator, Component, Node,instantiate, director } from "cc";
  2. const { ccclass, property } = _decorator;
  3. @ccclass("test")
  4. export class test extends Component {
  5. @property({type:Node})
  6. private target: Node = null;
  7. start(){
  8. let scene = director.getScene();
  9. let node = instantiate(this.target);
  10. node.parent = scene;
  11. node.setPosition(0, 0,-10);
  12. }
  13. }

创建预制节点

和克隆已有节点相似,你可以设置一个预制(Prefab)并通过 instantiate 生成节点。使用方法如下:

  1. import { _decorator, Component, Prefab, instantiate, director } from "cc";
  2. const { ccclass, property } = _decorator;
  3. @ccclass("test")
  4. export class test extends Component {
  5. @property({type:Prefab})
  6. private target: Prefab = null;
  7. start(){
  8. let scene = director.getScene();
  9. let node = instantiate(this.target);
  10. node.parent = scene;
  11. node.setPosition(0,0,0);
  12. }
  13. }

销毁节点

通过 node.destroy() 函数,可以销毁节点。值得一提的是,销毁节点并不会立刻被移除,而是在当前帧逻辑更新结束后,统一执行。当一个节点销毁后,该节点就处于无效状态,可以通过 isValid 判断当前节点是否已经被销毁。

使用方法如下:

  1. import { _decorator, Component, Node } from "cc";
  2. const { ccclass, property } = _decorator;
  3. @ccclass("test")
  4. export class test extends Component {
  5. @property({type:Node})
  6. private target: Node = null;
  7. private positionz: number = -20;
  8. start(){
  9. // 5秒后销毁节点
  10. setTimeout(function () {
  11. this.target.destroy();
  12. }.bind(this), 5000);
  13. }
  14. update(deltaTime: number){
  15. console.info(this.target.isValid);
  16. this.positionz += 1*deltaTime;
  17. if (this.target.isValid) {
  18. this.target.setPosition(0.0,0.0,this.positionz);
  19. }
  20. }
  21. }

destroy 和 removeFromParent 的区别

调用一个节点的 removeFromParent 后,它不一定就能完全从内存中释放,因为有可能由于一些逻辑上的问题,导致程序中仍然引用到了这个对象。因此如果一个节点不再使用了,请直接调用它的 destroy 而不是 removeFromParentdestroy 不但会激活组件上的 onDestroy,还会降低内存泄露的几率,同时减轻内存泄露时的后果。

总之,如果一个节点不再使用,destroy 就对了,不需要 removeFromParent 也不需要设置 parentnull 哈。


继续前往 资源管理/加载和切换场景 说明文档。