Simple script: Support for UI Element Group opacity

Hey guys!
As you probably know, by default opacity isn’t supported in UI Elements of type group, hence you can’t change global opacity of grouped UI elements, layouts, etc - neither in Editor nor in script, which is very inconvenient for UI tweening.

So I’ve created a simple script that would allow you to modify group opacity at runtime via scripting. Create a new JS script in your Editor, fill it in with content below, and make sure it’s marked to load After Engine. It supports nested Groups as well.

(() => {


pc.ElementComponent.prototype.findGroupParent = function ()
{
    let parent = this.entity.parent;

    while (parent)
    {
        if (parent.element?.type === 'group')
            return parent;
        else if (parent.element && parent.parent)
            parent = parent.parent;
        else
            return null;
    }

    return null;
};


Object.defineProperty (pc.ElementComponent.prototype, 'opacity',
{
    set (value)
    {
        this._opacity = value ?? 1;
        this._mult = 1;
        
        let parent = this.findGroupParent ();
        if (parent)
        {
            this._mult *= parent.element._opacity ?? 1;
            this._mult *= parent.element._mult ?? 1;
        }
        
        if (!this.mask)
            this._setValue ('opacity', this._opacity * this._mult);
        else
            this._setValue ('opacity', this._opacity);

        for (let child of this.entity.children)
            if (child.element)
                child.element.opacity = child.element.opacity;
    },
    get ()
    {
        return this._opacity;
    }
});


})();

Cheers!

5 Likes

Modified script above to support some edge cases when the element acts as a mask. In that case it should be always of opacity 1, otherwise the mask will render empty