[0]Laya3中怎么访问预制体内部的节点
我开发了一个预制体,命名为Title,其结构如图,只有2个节点
然后,我在Scene中使用这个Title预制体,Scene的结构如图
现在我打算在Scene中用代码访问Title预制体中的Label节点。
我想请问下,官方有什么办法直接访问预制体中的节点吗?
我能想到的方案就是,在Runtime或者Script中,通过遍历查找节点,方案代码如下:
麻烦解答一下,感谢!!
然后,我在Scene中使用这个Title预制体,Scene的结构如图
现在我打算在Scene中用代码访问Title预制体中的Label节点。
我想请问下,官方有什么办法直接访问预制体中的节点吗?
我能想到的方案就是,在Runtime或者Script中,通过遍历查找节点,方案代码如下:
function getComponentByName(node: Laya.Node, name: string): Laya.Node {[i][i] [/i][/i]
const children: Laya.Node = (node as any)._children;
for(let i = 0; i < children.length; i++) {
if (children.name === name) {
return children;
}
const found = getComponentByName(children, name);
if (found) {
return found;
}
}
return null;
}
export class Runtime extends RuntimeBase {
onAwake(): void {
const node = getComponentByName(this, 'label') as Laya.Label;
node.text = 'Runtime';
console.log(node);
}
}
export class Script extends Laya.Script {
onAwake(): void {
const node = getComponentByName(this.owner, 'label') as Laya.Label;
node.text = 'Script';
console.log(node);
}
}
麻烦解答一下,感谢!!
没有找到相关结果
已邀请:
要回复问题请先登录
2 个回复
Laya_Fred
赞同来自:
ystrdy
赞同来自:
在预制体中,如下操作
第一步,给预制体中需要访问的元素定义变量
第二步,给预制体添加Runtime
在场景中使用时,给预制体定义变量
当需要访问预制体中的元素时,分两种情况
一、在Runtime中访问
二、在Script中访问
在Script中访问需要注意的一点是,要记得声明owner的类型