cocos creator 调用预设体Prefab中的方法(调用另一个节点的方法)

调用预设体中的方法

  • 通过cc.instantiate(this.star)创建这个预设体实例
  • 这个star预设体中添加了一个脚本组件star.ts
    在这里插入图片描述
  • 获取到这个脚本组件star.getComponent(‘star’).test(),并调用其中的test()方法
  • 同理可以用该方式像另一个节点中传值
    //星星预设体
    @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)
        }
    }

调用另一个节点中的方法

cc
.find('background')//根据名字找到对应的节点
.getComponent('back')//找到节点中的脚本组件
.test()//调用脚本的中的test方法

cc
.find('background')//根据名字找到对应的节点
.getComponent(cc.Node)//找到节点中的节点组件

相关推荐

  1. Rust链式调用方法

    2024-02-02 00:26:02       23 阅读
  2. Go使用反射动态方法调用

    2024-02-02 00:26:02       31 阅读
  3. Vue.js 父组件调用子组件方法

    2024-02-02 00:26:02       30 阅读
  4. 在VUE页面调用Extjs定义方法

    2024-02-02 00:26:02       16 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-02 00:26:02       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-02 00:26:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-02 00:26:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-02 00:26:02       18 阅读

热门阅读

  1. Python 机器学习 K-近邻算法

    2024-02-02 00:26:02       38 阅读
  2. go语言-字符串处理的常用函数

    2024-02-02 00:26:02       27 阅读
  3. Docker

    2024-02-02 00:26:02       25 阅读
  4. go install

    2024-02-02 00:26:02       39 阅读
  5. Redis的过期策略和内存淘汰机制

    2024-02-02 00:26:02       29 阅读
  6. Spring Cloud Gateway 修改请求体、响应体

    2024-02-02 00:26:02       31 阅读
  7. 重回一年级,请问你们还知道余数是什么吗

    2024-02-02 00:26:02       25 阅读
  8. Git分布式版本控制系统

    2024-02-02 00:26:02       29 阅读
  9. 【LNMP】RHEL8.3安装LNMP并配置freetds连接MSSQL

    2024-02-02 00:26:02       30 阅读
  10. 【C语言】va_list(可变参数处理)

    2024-02-02 00:26:02       28 阅读
  11. 工厂方法入门

    2024-02-02 00:26:02       33 阅读