Cocos Creator 节点和组件的简单理解01

1:节点和组件的概念

    节点:在层级管理器中创建UI组件 2D 或3D ,空节点等 。  节点可以理解为 一个Dom,一个                       Button,或者   一个 HTML脚本。

    组件:在资源管理器上创建的ts, js 脚本, 物理材质 ,动画片段, 都是可以成为组件。 可以                  理解为 HTML引入的JS脚本 但不仅限于 脚本。

2:组件和节点的关系 

  父  : 当我在N_0 的之节点上绑定组件ts_0.ts时:如图所示

  ts_0.ts 代码如下:


import { _decorator, Component, Node, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Ts0')
export class Ts extends Component {

    // @property({ type: Label })
    // lable_0_2: Label | null = null;

    start() {
        let consoleTable = [

            {
                Input: "this.getComponentInChildren(Label)",
                result: this.getComponentInChildren(Label),
                descirpt: "Lable:Node类型,Ts01:Component组件类型"
            },
            {
                Input: "this.getComponentInChildren(Ts_0_1)",
                result: this.getComponentInChildren("Ts_0_1"),

                descirpt: " "
            },
            {
                Input: "this.getComponent(Ts_0_1)",
                result: this.getComponent("Ts_0_1"),
                descirpt: ""
            },
            {
                Input: "this.getComponent(Label)",
                result: this.getComponent(Label),
                descirpt: ""
            },

            {
                Input: "this.node.getComponents(Label)",
                result: this.node.getComponents(Label),
                descirpt: " "
            },
            {
                Input: "this.node.getComponentInChildren(Label)",
                result: this.node.getComponentInChildren(Label),
                descirpt: ""
            },
            {
                Input: "this.node.getComponentInChildren(Ts_0_1)",
                result: this.node.getComponentInChildren("Ts_0_1"),
                descirpt: " "
            },
            {
                Input: "this.node.getComponent(Ts_0_1)",
                result: this.node.getComponent("Ts_0_1"),
                descirpt: ""
            },
        ]
        console.table(consoleTable)
    }

    // update (deltaTime: number) {
    //     // [4]
    // }
}

子节点:绑定 TS_0_1.js组件

执行打印结果 输出:

 2  :接着把ts_0_1.js组件绑定到父节点N_0上:

 打印输出结果

总结:

1:可以看出 this.getComponent() 表示的是获取当前节点下的组件 ,如果当前节点没有绑定该组件,即便是子节点的组件也是获取不到的。想要获取子节点的组件必须通过this.getComponentInChildren('Ts_0_1') 才能获得。

2:想要获取子节点 ,第一种是通过引入变量的方式引入(推荐大家尽量使用第一种方式),第二种是通过this.getComponentInChildren(Node类型节点) 获得 

 3:this.node.getComponent() 节点上的 和 当前this上的 getComponent()的方法是等价的

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值