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)//找到节点中的节点组件
相关推荐
胡童嘉5 天前
长沙烈焰鸟网络科技有限公司实习day13日记
功能测试·学习·职场和发展·游戏引擎·cocos2d
神秘的土鸡8 天前
【CS创世SD NAND征文】为无人机打造可靠数据仓:工业级存储芯片CSNP32GCR01-AOW在飞控系统中的应用实践
嵌入式硬件·游戏引擎·无人机·cocos2d·雷龙
小时候的阳光22 天前
Cocos Creator 和 Unity 3D 编辑界面字体样式大小调整
unity·cocos2d·字体大小
mit6.82423 天前
[无人机sdk] Open Protocol | 协议包构造&验证
游戏引擎·无人机·cocos2d
锦瑟弦音24 天前
2048游戏开发笔记4 & 音效 cocos3.8.7
笔记·typescript·cocos2d
FairGuard手游加固1 个月前
Cocos资源加密方案解析
安全·游戏·cocos2d
应用市场1 个月前
无人机编队飞行原理与Python仿真实现完整指南
python·无人机·cocos2d
云卓SKYDROID1 个月前
无人机中继器模式技术对比
人工智能·游戏引擎·php·无人机·cocos2d·高科技·云卓科技
重生之我在永职2 个月前
cocos 添加背景,帧动画,贴图
cocos2d
山外有山a2 个月前
《黑神话:悟空》核心攻略指南 如何在mac苹果电脑运行《黑神话:悟空》
macos·cocos2d·改行学it