cocos creator 调用预设体Prefab中的方法(调用另一个节点的方法)

调用预设体中的方法

  • 通过cc.instantiate(this.star)创建这个预设体实例
  • 这个star预设体中添加了一个脚本组件star.ts
  • 获取到这个脚本组件star.getComponent('star').test(),并调用其中的test()方法
  • 同理可以用该方式像另一个节点中传值
js 复制代码
    //星星预设体
    @property(cc.Prefab)
    star: cc.Prefab = null;

    createStar(parent: cc.Node) {
        //创建星星之前,要先清理掉之前的星星
        parent.removeAllChildren(true)
        for (let i = 0; i < this.screenItemNum; i++) {
            let star = cc.instantiate(this.star)
            star.getComponent('star').test()
            this.srcWidth = star.width * star.scale
            star.y = Math.random() * (this.screenItemHeight - this.srcWidth) + this.srcWidth / 2 + this.screenItemHeight * i
            star.x = Math.random() * (this.screenWidth - this.srcWidth) + this.srcWidth / 2
            star.setParent(parent)
        }
    }

调用另一个节点中的方法

js 复制代码
cc
.find('background')//根据名字找到对应的节点
.getComponent('back')//找到节点中的脚本组件
.test()//调用脚本的中的test方法

cc
.find('background')//根据名字找到对应的节点
.getComponent(cc.Node)//找到节点中的节点组件
相关推荐
怣疯knight5 小时前
Cocos creator判断节点是否能用的方法
unity·cocos2d
Doc.S1 天前
多无人机任务自定义(基于ZJU-FAST-Lab / EGO-Planner-v2)
游戏引擎·无人机·cocos2d
天途小编1 天前
无人机操控模式解析:美国手、日本手、中国手
游戏引擎·无人机·cocos2d
Unity打怪升级5 天前
【Unity精品源码】Ultimate Character Controller:高级角色控制器完整解决方案
游戏·unity·ue5·游戏引擎·godot·游戏程序·cocos2d
7***n7520 天前
C++在游戏中的Cocos2d-x
游戏·游戏引擎·cocos2d
Marvin_Kai20 天前
Cocos Creator 3.x 实现“粒子特效” 的 点击触发
cocos2d
胡童嘉1 个月前
长沙烈焰鸟网络科技有限公司实习day13日记
功能测试·学习·职场和发展·游戏引擎·cocos2d
神秘的土鸡1 个月前
【CS创世SD NAND征文】为无人机打造可靠数据仓:工业级存储芯片CSNP32GCR01-AOW在飞控系统中的应用实践
嵌入式硬件·游戏引擎·无人机·cocos2d·雷龙
小时候的阳光1 个月前
Cocos Creator 和 Unity 3D 编辑界面字体样式大小调整
unity·cocos2d·字体大小
mit6.8241 个月前
[无人机sdk] Open Protocol | 协议包构造&验证
游戏引擎·无人机·cocos2d