cocoscreator怎么获取所有节点
遍历cc.director.getScene().children
根据当前场景 怎么根据节点名字获取他属性和值 能在浏览器控制器里输出的
cc.log(this.node.getChildByName(xxx))
那如果已知 childName,parentNode.通过递归查询多层之下的某一个节点,是否存在风险。
你是打算找出指定名称的单个子节点,还是所有同名子节点?
一般两种运用场景吧。
1、父节点作用域中没有相同节点名:初始构建节点的时候,就设定好所有节点名称不同,这样查找后返回唯一值。
2、存在相同的节点名:那就把所有同名节点放在一个数组中返回。
主要考虑的是:使用递归查询处理的话,会不会存在未知风险。有没有经过验证的成熟方案。
findChildrensByName(node: cc.Node, name: string): cc.Node[] {
let ret = [];
let findChildrens = (node: cc.Node) => {
for (let i = node.childrenCount - 1; i > -1; --i) {
let children = node.children[i];
children.name === name && ret.push(children);
findChildrens(children);
}
}
findChildrens(node);
return ret;
}
谢谢啦。自己写的和你的逻辑大致一样,不过你经过项目验证过的,用你的了。哈哈。只是好奇除了递归,还有没有其他什么方案
export function findChildrens(node: cc.Node, name: string, isStartWith: boolean = false): cc.Node[] {
let ret = [];
let find = isStartWith ? (node: cc.Node) => {
for (let i = node.childrenCount - 1, childrens = node.children; i > -1; --i) {
let children = childrens[i];
children.name.startsWith(name) && ret.push(children);
find(children);
}
} : (node: cc.Node) => {
for (let i = node.childrenCount - 1, childrens = node.children; i > -1; --i) {
let children = childrens[i];
children.name === name && ret.push(children);
find(children);
}
}
find(node);
return ret;
}
这种需求用递归是最优解,别纠结了。
优化了一版,这样比较有用。
第3个参数传入true可以查找所有以特定字符开头的节点。
非递归遍历所有节点
visitNode(node: cc.Node, callback: (node: cc.Node) => void) {
let cur: cc.Node = null;
const queue = [node];
while (queue.length > 0) {
cur = queue.pop();
callback(cur);
queue.push(...cur.children);
}
}
这个两个参数都是node的命名,额~ 有点不太阅读。但是方案有说法。感谢