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)//找到节点中的节点组件
相关推荐
weixin_409383128 天前
cocos shader闪光
游戏引擎·cocos2d
weixin_409383128 天前
cocos shader三角流光
游戏引擎·cocos2d
weixin_409383129 天前
cocos shader流光文字 不显示透明部分
游戏引擎·cocos2d
CodeCaptain15 天前
Cocos Creator 3.8.x 可对tiled 1.4.x进行的操作或分析有哪些
经验分享·游戏·typescript·cocos2d
CodeCaptain16 天前
CocosCreator3.8.x 解析Tiled1.4.x【瓦片图层、对象图层、图像图层、组图层】的核心原理
经验分享·游戏·typescript·cocos2d
wgc2k17 天前
从明码 CSV 到 AES 加密 TXT:Cocos3.8 游戏数据加密实践
cocos2d
CodeCaptain19 天前
Cocos Creator 3.8.0 官方文档明确支持 Tiled Editor v1.4 版本,也兼容 1.4.x 小版本(如1.4.3)
cocos2d
怣疯knight19 天前
cocos creator 的几个变量显示写法
cocos2d
CodeCaptain19 天前
Cocos Creator3.8.0 Tiled地图三合一完整脚本(加载+兼容性校验+坐标互转,一键可用,适配Tiled1.4.x)
游戏·cocos2d
CodeCaptain19 天前
一个快速校验地图资源是否符合兼容要求的小脚本(Cocos Creator3.8.0)
游戏·typescript·cocos2d