节点置灰

版本:cocos creator 3.8
节点包括所有子节点置灰的方法:如下:直接上代码了
setGray(target: Node | Sprite | Label, gray: boolean) {

    if (target instanceof Node) {

        target.walk((child) => {

            const spr = child.getComponent(Sprite)

            const lab = child.getComponent(Label)

            spr && this.setGray(spr, gray)

            lab && this.setGray(lab, gray)

        })

    } else if (target instanceof Sprite) {

        target.grayscale = gray;

    } else if (target instanceof Label) {

        if (gray) {

            const mat = builtinResMgr.get<Material>('ui-sprite-gray-material')

            target.customMaterial = mat

        } else {

            target.customMaterial = null;

        }

    }

}
5赞

以前做节点置灰最烦的是 Label 组件有 LabelOutline。楼主这个方法能解决这个问题,不过如果传入的 Label 有使用自定义材质的话是不是也寄了。

特殊情况特殊处理,可以增加一个回调,解决这个问题 如下:
static setGray(target: Node | Sprite | Label, gray: boolean, func?: (target: any) => Material) {

    if (target instanceof Node) {

        target.walk((child) => {

            const spr = child.getComponent(Sprite)

            const lab = child.getComponent(Label)

            spr && this.setGray(spr, gray,func)

            lab && this.setGray(lab, gray,func)

        })

    } else if (target instanceof Sprite) {

        target.grayscale = gray;

    } else if (target instanceof Label) {

        if (gray) {

            const mat = builtinResMgr.get<Material>('ui-sprite-gray-material')

            target.customMaterial = mat

        } else {

            target.customMaterial = func?.(target) || null;

        }

    }

}
2赞

我是这样写的,这样更加简洁 :grinning:
/**

 * 节点置灰

 */

protected setGray(node: Node, isGray: boolean): void {

    if(node == null || node.isValid == false){

        return;

    }

    let material:Material = builtinResMgr.get(isGray ? "ui-sprite-gray-material": "");

    let renders = node.getComponentsInChildren(UIRenderer);

    for(let i = 0; i < renders.length; i++){

        renders[i].customMaterial = material;

    }

}
6赞

自己体会 if (this.customMaterial !== null) :rofl: :rofl: :rofl:

如果字节点是个spine动画,怎么办

这只能说明引擎提供的功能就是一坨。。。