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)//找到节点中的节点组件
相关推荐
playmak3r16 天前
某手游cocos2dlua反编译
游戏引擎·lua·cocos2d
Coovally AI模型快速验证1 个月前
AI+无人机如何守护濒危物种?YOLOv8实现95%精准识别
人工智能·神经网络·yolo·目标检测·无人机·cocos2d
Coovally AI模型快速验证1 个月前
基于YOLO-NAS-Pose的无人机象群姿态估计:群体行为分析的突破
人工智能·神经网络·算法·yolo·目标检测·无人机·cocos2d
寻找优秀的自己1 个月前
Cocos 打包 APK 兼容环境表(Android API Level 10~15)
android·cocos2d
GameTomato1 个月前
【IOS】【OC】【应用内打印功能的实现】如何在APP内实现打印功能,连接本地打印机,把想要打印的界面打印成图片
macos·ios·objective-c·xcode·游戏开发·cocos2d
風吹过2 个月前
A* (AStar) 寻路
typescript·cocos2d
李詹2 个月前
游戏哪些接口会暴露源IP?_深度解析服务器通信安全隐患
游戏·游戏引擎·cocos2d·3dcoat
Delphi菜鸟3 个月前
go+mysql+cocos实现游戏搭建
mysql·游戏·golang·gin·cocos2d
wkj0013 个月前
Cocos Creator 进行 Web 发布后,目录结构解析
cocos2d
寻找优秀的自己3 个月前
主相机绑定小地图
cocos2d