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)//找到节点中的节点组件
相关推荐
洛阳吕工6 天前
从 micro-ROS 到 px4_ros2:ROS2 无人机集成开发实战指南
游戏引擎·无人机·cocos2d
SmartRadio9 天前
NRF52833 + MPU6050 室内定位跟随无人机
游戏引擎·无人机·cocos2d
howlet213 天前
AI生成cocos-creator打砖块游戏-跑通第1关(CodeBuddy)
人工智能·游戏·cocos2d
The森20 天前
cocos2d-x棋牌项目-模块2:GameView、Node 与 zOrder
游戏引擎·cocos2d
十五年专注C++开发22 天前
Cocos2d - x: 一款开源跨平台 2D 游戏框架
运维·c++·游戏·开源·游戏引擎·cocos2d
crazyJialin25 天前
聊聊一个游戏是怎么做出来的
游戏·cocos2d
The森1 个月前
macOS 26(M芯片)部署 cocos2d-x(C++)全链路指南——Xcode + Rosetta
c++·经验分享·笔记·macos·xcode·cocos2d
机器学习之心1 个月前
基于动态三维环境的Q‑Learning无人机自主避障路径规划的完整MATLAB实现
matlab·无人机·cocos2d
wearegogog1231 个月前
ESP32迷你无人机开发代码详解
游戏引擎·无人机·cocos2d
林鸿群1 个月前
VS2026 编译 Cocos2d-x 项目完整指南:解决兼容性问题
游戏引擎·cocos2d