cc.resources.load封装之后出现问题

  • Creator 版本: 2.4.5

用cc.resources.load加载图片写在onload里面一切正常,然后封装到方法里边之后出现问题了,请大佬们帮忙看看。

creatNode(name) {
    let node = new cc.Node(name);
    node.parent = this.node;
    return node;
},

loadPic(index) {
    let fileName = "'zhengtu_" + index + "'";
    cc.log(fileName);
    cc.resources.load(fileName, cc.Texture2D, (err, texture) => {
        this.picTexture = texture;
        cc.log(this.picTexture);
    });
},

onLoad() {
    this.picOrder = 0;
    this.loadPic(this.picOrder);

    let thumbnail = this.creatNode('thumbnail');
    let thumbnailSprite = thumbnail.addComponent(cc.Sprite);
    cc.log(this.picTexture);
    thumbnailSprite.spriteFrame = new cc.SpriteFrame(this.picTexture);
    thumbnail.scale = 0.5;
    thumbnail.opacity = 100;
},

问题一,上边的picLoad方法里边fileName打印出来的结果是’zhengtu_0’,加载不了图片,然后我直接把这个复制进cc.resources.load方法里就可以正常加载到图片,不太明白这是为什么
问题二,在picLoad方法里把texture赋值给this.picTexture后,方法里打印的this.picTexture是对的,但是在方法外的this.picTexture的打印结果是undefined,我尝试在onload里边picLoad方法之前定义一个this.picTexture=new cc.texture2D,结果方法外的this.picTexture也还是一样没有加载到图片
还请大佬帮忙看看是什么问题,谢谢了

loadPic(index) {
let fileName = “'zhengtu_” + index + “’”;
cc.log(fileName);
let self=this;
cc.resources.load(fileName, cc.Texture2D, (err, texture) => {
self.picTexture = texture;
cc.log(this.picTexture);
});
}

cc.resources.load(fileName, cc.Texture2D, (err, texture) => {
this.picTexture = texture;
cc.log(this.picTexture);
});

这个load的回调方法是异步的呀,onLoad里面刚刚调完loadPic这个方法,下面就在取 this.picTexture 这个变量是有问题的,这个时候 this.picTexture 还没被赋值呢,你可以看看你回调里面的打印是不是最后一个输出来的就造了

我试过用self了,不管用,在cc.resources.load里边用fileName变量也还是不行

用es6的async await不就好了

load里边的文件名用filename变量不能获取文件这个是因为什么

cc.resources.load是异步方法,当前帧拿不到结果 :joy:

用这位老哥说的就可以了

你的filename为啥要多加两个单引号

文件名是 zhengtu_0 在load里边 不得是’zhengtu_0’么

把单引号去掉确实可以了,不过还是不懂为什么,谢谢大佬

image 多了路径就不对了

let fileName = “zhengtu_” + index;
你换成这个样子就对了
你之前那种写法,其实fileName的值为’zhengtu_0’
你的图片名字应该是没有那俩单引号的吧

谢谢大佬帮忙

谢谢大佬,现在研究一下async await

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。