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()的方法是等价的