Cocos Creator 源码解读:siblingIndex 与 zIndex

直接用z吗

怎么那么多人鄙视zIndex的?是需求做的太少了吧?zIndex在某些情况下会比setSiblingIndex好用多了。

2d ui有z的概念么?

3.0可以用uiTransform的priority 虽然这个在3.1也被废除了 不过可以先用着

那3.1只有setSiblingIndex了,怎么实现之前zIndex或者priority的类似功能呢?

priority还可以用。如果要自己实现会很麻烦。其实就是类似uitransform的priority那样实现一套。然后所有ui还要有这个组件

UI上排序确实不好用,动态增加节点要计算插到第几个位置,还不好计算。而zIndex是代码宏定义出来的,不用计算。

1赞

这个话题应该可以中终结了,用UItransform组件里面priority属性,和zindex功能一致

3.3后面的版本 priority 已经被抛弃了,哈哈
我刚模拟了个zIndex写法,在onLoad中,需要排序的节点children全部设置一遍setZIndex。
后面随意调用setZIndex动态设置zIndex。

不牵扯排序的节点children不用调用此方法。

//设置zIndex
setZIndex(node: Node, zIndex: number) {
(node as any).zIndex = zIndex;
let bFindMe = false;
let parent = node.parent;
if(!parent){
console.log(‘no parent,please check code!’);
return;
}
let children = parent.children;
for (let i = children.length - 1; i >= 0; --i) {
let child = children[i];
if (node == child) {
bFindMe = true;
} else {
let chIndex = (child as any).zIndex;
if (typeof chIndex != ‘number’) chIndex = 0;
if (zIndex >= chIndex) {
node.setSiblingIndex(bFindMe ? i + 1 : i);
break;
}
}
}
// let str = ‘’;
// for(let i=0;i<children.length;++i){
// str += ‘,’+children[i].name+’:’+(children[i] as any).zIndex;
// }
// console.log(str);
}

1赞

刚试了下3.3.2版本,可以使用priority 属性,并有效,测的是web,原生还没测
当然项目设置—》功能裁剪—》废弃接口的√要去掉

废弃接口就不用了,后面升级项目,又是一堆问题,还是用setSiblingIndex比较好。

这个方法直接数组排序,这样的性能表现会好很多

如果只是简单UI就还好,如果是地图和战斗,根本就用不了setSiblingIndex

    /** 根据zIndex统一设置节点顺序 */
    public static setChildrenNodeSortByZIndex(parent: Node): void {
        if (!parent) {
            return;
        }

        let children = parent.children.concat();
        children.sort((a, b): number => {
            if (a.zIndex == null) {
                a.zIndex = 0;
            }
            if (b.zIndex == null) {
                b.zIndex = 0;
            }
            return a.zIndex - b.zIndex;
        });
        let maxIndex = children.length;
        for (const node of children) {
            node.setSiblingIndex(maxIndex);
        }
    }
1赞

感觉大佬分享
3.4.2,我想动态调整同一父节点下子节点的层级,但zIndex,priority好像都去掉了,setSiblingIndex设置没有用,这要怎么处理,有些懵

大佬牛啤 :beers: :beers:

我上面的评论不是可以设置吗?没有zIndex就自己声明一个
不知道怎么声明:直接上代码。

declare module "cc" {
    interface Node {
        /** 借助它实现2.x层级效果,直接赋值不会有任何效果 */
        zIndex: number;
    }
}

image

1赞

好的,感谢感谢,我来试下

MARK!!!

唉,还是以前2dx直接设置zOrder方便好用,现在这个siblingIndex真不方便,而且只能是同级下的排序,如果有特殊情况不在同级,这会很抓狂