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)//找到节点中的节点组件
相关推荐
jumu2022 天前
COMSOL凝固模拟:从溶质偏析到枝晶生长实战
cocos2d
z2014z2 天前
Cocos Creator Playable 广告项目文件夹结构与命名规范
cocos2d
怣疯knight3 天前
Cocos creator如何使用onCollisionEnter或者onTriggerEnter
cocos2d
怣疯knight5 天前
Cocos creator判断节点是否能用的方法
unity·cocos2d
Doc.S5 天前
多无人机任务自定义(基于ZJU-FAST-Lab / EGO-Planner-v2)
游戏引擎·无人机·cocos2d
天途小编6 天前
无人机操控模式解析:美国手、日本手、中国手
游戏引擎·无人机·cocos2d
Unity打怪升级9 天前
【Unity精品源码】Ultimate Character Controller:高级角色控制器完整解决方案
游戏·unity·ue5·游戏引擎·godot·游戏程序·cocos2d
7***n7524 天前
C++在游戏中的Cocos2d-x
游戏·游戏引擎·cocos2d
Marvin_Kai25 天前
Cocos Creator 3.x 实现“粒子特效” 的 点击触发
cocos2d
胡童嘉1 个月前
长沙烈焰鸟网络科技有限公司实习day13日记
功能测试·学习·职场和发展·游戏引擎·cocos2d