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)//找到节点中的节点组件
相关推荐
crazyJialin3 天前
聊聊一个游戏是怎么做出来的
游戏·cocos2d
The森4 天前
macOS 26(M芯片)部署 cocos2d-x(C++)全链路指南——Xcode + Rosetta
c++·经验分享·笔记·macos·xcode·cocos2d
机器学习之心5 天前
基于动态三维环境的Q‑Learning无人机自主避障路径规划的完整MATLAB实现
matlab·无人机·cocos2d
wearegogog1238 天前
ESP32迷你无人机开发代码详解
游戏引擎·无人机·cocos2d
林鸿群11 天前
VS2026 编译 Cocos2d-x 项目完整指南:解决兼容性问题
游戏引擎·cocos2d
林鸿群11 天前
VS2026 编译 Cocos2d-x 老项目完整指南:从崩溃到完美运行
游戏引擎·cocos2d
IT猿手12 天前
基于四旋翼无人机离散建模与增量PID控制及轨迹跟踪研究,MATLAB代码
开发语言·matlab·无人机·cocos2d·路径规划·动态路径规划
国科安芯15 天前
星载电源遥测模块抗辐照RISC-V MCU的性能适配与应用
单片机·嵌入式硬件·无人机·cocos2d·risc-v
林鸿群16 天前
Cocos2d-x v4 官方文档学习总结
学习·游戏引擎·cocos2d
林鸿群16 天前
Cocos2d-x 官方仓库学习总结
学习·游戏引擎·cocos2d