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