【cocos creator】【TS】资源加载类,图片置灰

// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class resLoadMgr extends cc.Component {
    static instance: resLoadMgr;

    @property(cc.Material)
    private normalSprite: cc.Material = null;   // 正常颜色
    @property(cc.Material)
    private graySprite: cc.Material = null;     // 灰色

    @property(cc.Node)
    private testNode: cc.Node = null;     // 灰色
    onLoad() {
        resLoadMgr.instance = this;
    }

    start() {

    }


    //加载界面
    loadPanel(prefabPath: string, cb: (res: cc.Prefab) => void) {
        cc.loader.loadRes("uiPanel/" + prefabPath, cc.Prefab, (err, res) => {
            if (err) {
                console.error(err);
                return cb(null);
            }
            cb(res);
        });
    }


    // 加载骨骼动画
    loadSkeleton(path: string, cb: (data: sp.SkeletonData) => void) {
        cc.loader.loadRes(path + "/Project", sp.SkeletonData, (err, res) => {
            if (err) {
                console.error(err);
                return cb(null);
            }
            cb(res);
        });
    }

    //加载图片
    loadImg(url, cb: (img: cc.SpriteFrame) => void) {
        cc.loader.loadRes(url, cc.SpriteFrame, (err, sprite) => {
            if (err) {
                //console.error(err);
                return cb(null);
            }
            cb(sprite);
        });
    }

    // 头像
    loadHeadImg(id: number, cb: (img: cc.SpriteFrame) => void) {
        this.loadImg("headImg/" + id, cb);
    }

    //设置图片状态(图片置灰)
    setNodeState(node: cc.Node, isGray: boolean) {
        let mtl = isGray ? this.graySprite : this.normalSprite;
        let render = node.getComponent(cc.Sprite);
        if (render) {
            render.setMaterial(0, mtl);
        }
        for (let one of node.children) {
            this.setNodeState(one, isGray);
        }
    }

    //_____________使用________________
    test() {
        resLoadMgr.instance.loadHeadImg(1, (img) => {
            if (cc.isValid(this)) {
                this.testNode.getComponent(cc.Sprite).spriteFrame = img;
            }
        });
        resLoadMgr.instance.loadSkeleton("jump", (res) => {
            this.testNode.getComponent(sp.Skeleton).skeletonData = res;
        });
        resLoadMgr.instance.loadPanel("panel", (res) => {
            var node = cc.instantiate(res);
            node.parent = cc.Canvas.instance.node;//canvas节点
        });
        resLoadMgr.instance.setNodeState(this.testNode, false);
    }
    // update (dt) {}
}

你可能感兴趣的:(cocos)