首页 > 其他分享 >Cocos Creator开发中的instantiate方法小结

Cocos Creator开发中的instantiate方法小结

时间:2023-05-21 10:06:24浏览次数:51  
标签:Node node Cocos Creator EventType instantiate Prefab item

简介

instantiate方法在Cocos Creator中有两种作用:

  • 从 Prefab 实例化出新节点
  • 克隆指定的任意类型的对象

对应于框架源代码中的文字介绍如下:

    /**
     * @zh 从 Prefab 实例化出新节点。
     * @en Instantiate a node from the Prefab.
     * @param prefab The prefab.
     * @returns The instantiated node.
     * @example
     * ```ts
     * import { instantiate, director } from 'cc';
     * // Instantiate node from prefab.
     * const node = instantiate(prefabAsset);
     * node.parent = director.getScene();
     * ```
     */
    export function instantiate(prefab: Prefab): Node;
    /**
     * @en Clones the object `original.
     * @zh 克隆指定的任意类型的对象。
     * @param original An existing object that you want to make a copy of.
     * It can be any JavaScript object(`typeof original === 'object'`) but:
     * - it shall not be array or null;
     * - it shall not be object of `Asset`;
     * - if it's an object of `CCObject`, it should not have been destroyed.
     * @returns The newly instantiated object.
     * @example
     * ```ts
     * import { instantiate, director } from 'cc';
     * // Clone a node.
     * const node = instantiate(targetNode);
     * node.parent = director.getScene();
     * ```
     */
    export function instantiate<T>(original: T): T;
    export namespace instantiate {
        export var _clone: typeof __private._cocos_serialization_instantiate__doInstantiate;
        export var _clone: typeof __private._cocos_serialization_instantiate__doInstantiate;
    }

从 Prefab 实例化出新节点

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

import { _decorator, Component, Prefab, instantiate, director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass("test")
export class test extends Component {

    @property({type:Prefab})
    private target: Prefab = null;

    start(){
        let scene = director.getScene();
        let node = instantiate(this.target);

        scene.addChild(node);
        node.setPosition(0,0,0);
    }
}

需要注意的是,在使用上述的代码时,需将持有该代码的脚本挂在某个节点上,并在 属性检查器 内配置好 target 的值。

操作Prefab对象数组的举例

注:本例程改编自官方示例工程中的event-first场景,修改后的代码如下:

import { _decorator, Component, Node, instantiate, EventTouch, Prefab, Label, Button,Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;


@ccclass('eventFirst')
export class eventFirst extends Component {

    @property({
        type: Prefab,
    })
    public prefabNode: Prefab = null!;

    @property({
        type:Label
    })
    public labelShow: Label = null!;

    @property({
        type: Button,
    })
    public button: Button = null!;

    // @property({
    //     type: Node,
    // })
    //public items: Node[] = null!;//XXXXXX
    public items: Node[] = [];
    
    private static times: number=0;
    public i: Node=null!;

    onl oad () {
        this.i=instantiate(this.prefabNode);

        this.items.push(this.i);//TypeError: Cannot read property 'push' of null

        eventFirst.times++;

        console.log("eventFirst.times: ", eventFirst.times);
    }

    start () {
        // Your initialization goes here.
    }

    onEnable() {
        this.eventOn();
    }

    eventOn() {
        this.i.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.i.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.i.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.i.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);

        this.node.addChild(this.i);
        console.log("addChild(this.i) ");


    }

    onDisable() {
        this.items.forEach(item => {
            item.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
            item.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
            item.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            item.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
           
        });
    }

    onTouchStart(event: EventTouch){
        this.labelShow.string = `TouchStart: ${event.getLocation()}`;
        console.log(`TouchStart: ${event.getLocation()}`);
    }

    onTouchMove(event: EventTouch){
        this.labelShow.string = `TouchMove: ${event.getLocation()}`;
        console.log(`TouchMove: ${event.getLocation()}`);
    }

    onTouchEnd(event: EventTouch){
        this.labelShow.string = 'TouchEnd';
        console.log('TouchEnd');
    }

    onTouchCancel(event: EventTouch){
        this.labelShow.string = 'TouchCancel';
        console.log('TouchCancel');
    }

    createChild() {
        console.log("eventFirst.times: ", eventFirst.times++);

        let item = instantiate(this.prefabNode);
        item.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        item.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        item.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        item.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);

        let tmpItem=this.items[this.items.length-1];
        item.setPosition(new Vec3(tmpItem.position.x+90,
            tmpItem.position.y));
        this.items.push(item);

        this.node.addChild(item);

    //    this.button.node.active = false;
    }
}

这是实战场景中动态创建Prefab对象的方案之一,仅供参考。


克隆指定的任意类型的对象

有时我们希望动态的克隆场景中的已有节点,我们可以通过 instantiate 方法完成。注意事项:

要克隆的JavaScript对象可以是任何JS对象(`typeof original === 'object'`) ,但是:

    * 不是能数组或者null。

    * 也不是能Asset类型的对象。

    *如果是一个CCObject类型的对象,那么被克隆的母对象不能已被销毁。

来自于官方地址的简单应用举例如下:

import { _decorator, Component, Node,instantiate, director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass("test")
export class test extends Component {

    @property({type:Node})
    private target: Node = null;

    start(){
        let scene = director.getScene();
        let node = instantiate(this.target);

        scene.addChild(node);
        node.setPosition(0, 0,-10);
    }
}



参考

https://docs.cocos.com/creator/manual/zh/scripting/create-destroy.html


标签:Node,node,Cocos,Creator,EventType,instantiate,Prefab,item
From: https://blog.51cto.com/zhuxianzhong/6318604

相关文章

  • Qt Creator 你必须要掌握的快捷操作
    多使用快捷键能显著提高工作效率,尽可能减少键盘,鼠标之间切换所浪费的时间。我这里列出个人认为非常重要必须掌握的 QtCreator 快捷键。看你知道几个?.1.Ctrl(按住)+Tab快速切换已打开的文件 .2.快速添加方法实体(.cpp)声明,将光标移动到h文件中的方法声明。按Alt(按住)+E......
  • QtCreator中常用快捷键总结
    F1                        查看帮助F2                        跳转到函数定义(和Ctrl+鼠标左键一样的效果)Shift+F2               声明和定义之间切换F4                       头文......
  • 【Cocos2d游戏开发之四】独自收集Cocos2d提供的字体!共57种(有对照的字体图)...
     很多游戏中,便于开发就会直接采用Cocos2d提供的字体库来使用,但是因为提供的种类很多,那么Himi利用一些时间整理了57种字体样式,这些我想足够你用了;不多说下面一起来看看吧:(每张图对应11种样式的字体,字体的名字就是其样式的名字)   ---------------1------------------CCLabelTTF*myLabel=[CCLabelTTFlabelWithS......
  • 【Cocos2d游戏开发之七】添加/删除系统组件,并解决View设置透明会影响View中的其他组件
    好像有段时间没有更新了,主要项目比较着急,不过现在cocos2d基本算是全拿下了,进展很顺利,那么在这里主要给大家介绍下一些Himi遇到的问题;本章介绍两个知识点:        1.在Cocos2d中添加系统组件;(本例中添加UIView并嵌套一些View)  “   如何把背景图片设置为半透明......
  • 【Cocos2d游戏开发之九】CCSpriteBatchNode与"pvr.ccz","plist"精灵优化及注意事项
     首先对于使用过精灵的童鞋很熟悉CCSpriteBatchNode,至少大家都会知道它能优化精灵,但是至于优化原理这里简单说下:      一般使用精灵CCSprite的时候,都是直接使用[CCLayer*addChild:CCSprite*];,假设我们创建一百个精灵,那么当前的CCLayer会为100个精灵单独绘制;  ......
  • cocos 游戏开发项目中注意事项
    1、用vscode编辑代码的配置CocosDashboard.exe  打开后,在文件=》设置=》数据编辑=》外部脚本编辑选择vscode的code.exe  例如:自己的 C:\Users\自己的电脑用户名\AppData\Local\Programs\MicrosoftVSCode 下后保存即可,后期可用vscode编辑代码2、在vscode中编辑代......
  • cocos creator 快速生成apk
    #!/usr/bin/python#coding:utf8importosimportsysimportreimportexecjs,timecurFilepath=os.path.realpath(__file__)storeFile=os.path.join(os.path.split(curFilepath)[0],'xxx.keystore')samsung='samsung'MTPProjectPath=o......
  • Windows中qtcreator怎么将编译路径更改为当前目录?
       像VC那样,将执行文件所在debug或release目录,放置到源文件的当前目录是不错的选择。因为便于查找。   要实现这个将编译路径更改为当前目录功能,其实很简单,只需要在项目属性页的“构建目录”所在的编辑框中输入“./”即可。   此时,会在源文件的当前目录中产生......
  • Gitee自动部署 cocoscreator web端
    Gitee自动部署参考文档:Gitee目前支持特性:推送代码到Gitee时,由配置的WebHook触发Jenkins任务构建。评论提交记录触发提交记录对应版本Jenkins任务构建提交PullRequest到Gitee项目时,由配置的WebHook触发Jenkins任务构建,支持PR动作:新建,更新,接受,关闭,审查通过,测试......
  • 龙芯派二代2k1000la开发——交叉编译环境搭建(C/C++和Qtcreator)
    龙芯派二代2k1000la开发——交叉编译环境搭建(C/C++和Qtcreator)一、下载脚本文件这个脚本文件可以在龙芯技术支持QQ群中找到二、编译C/C++程序在下载目录下执行该脚本./poky-glibc-x86_64-my-qt5-image-loongarch64-ls3a5000-toolchain-3.3+snapshot.shBash设置环境变量source/opt......