[SOLVED] Setting texture of spriteFrame applies to all instances

Dear fellow cocos2d-ers,

I’m working on a card game so I decided to take the advantages of Cocos Creator.
Unfortunately I ran into some strange behaviour when I tried to set the new texture on my card.

I’ve created a Card node which has the following node tree:

Card
> Back
    Background
    Type
> Front
    ...

This way I could nicely set the sizes, positions and some default sprite frames for Background and Type nodes.
The Card node has the script component named game.scene.card.

So first I create a new Card node somewhere:

var sprite = cc.instantiate(this.CardNode);
this.node.addChild(sprite);
sprite.getComponent('game.scene.card').init(
    ...
);

Then the init method on the game.scene.card script changes the texture of the child nodes:

var url = cc.url.raw("resources/card/nicePic.png")
var texture = cc.textureCache.addImage(url);
var sprite = this.getChildByName('Back').getChildByName('Type').getComponent(cc.Sprite);

sprite.spriteFrame.setTexture(texture);

And this is the point where I’m totally stuck.
Upon the new spriteFrame is loaded it appears on the predefined Card node and disappears from the newly created/instantiated one.

I’ve tried an other method according to the API:

cc.loader.load(url, function (err, spriteFrame) {
    this.spriteFrame = spriteFrame;
}.bind(this.getChildByName('Back').getChildByName('Type').getComponent(cc.Sprite)));

In this case I get an error: Uncaught TypeError: this._spriteFrame.textureLoaded is not a function
when the CCSprite.js tries to load the spriteFrame here:

_applySpriteFrame: function (oldFrame) {
        ...
        if (this._spriteFrame) {
            if (this._spriteFrame.textureLoaded()) {
        ...

I’ve tried to reproduce the issue on the HelloWorld project.
What happens is when I set the new texture it applies to instantiated node and all the instances.

The HelloWorld script looks like this:

onLoad: function () {
    this.label.string = this.text;
    
    var url = cc.url.raw("resources/1.png");
    var texture = cc.textureCache.addImage(url);
    
    var sprite = cc.instantiate(this.node.getChildByName('cocos'));
    sprite.getComponent(cc.Sprite).spriteFrame.setTexture(texture);
    this.node.addChild(sprite);
    sprite.x = 300;
    
    var url2 = cc.url.raw("resources/2.png");
    var texture2 = cc.textureCache.addImage(url2);
    
    var sprite2 = cc.instantiate(this.node.getChildByName('cocos'));
    sprite2.getComponent(cc.Sprite).spriteFrame.setTexture(texture2);
    this.node.addChild(sprite2);
    sprite2.x = -300;
}

The result looks like this:

1 Like

Well.

sprite.spriteFrame = new cc.SpriteFrame(texture);

has solved the problem both on the HelloWorld and on my project.
I’ve tried this before, so I must have miswritten something then.
So that’s it. I hope at least someone finds it helpful in the future.

4 Likes

so should we consider this a bug?

Please no :slight_smile: