Add Sprite to the Scene

Hi, I stopped using Cocos since 3.8 (C++). Today, I try cocos creator with “Hello world example”, but I can’t add cc.Sprite to Scene (HelloWorld.js). I don’t want add a Sprite Component Properties, is it possible to add simple Sprite into Scene?
This is my Code and error after //

cc.Class({
    extends: cc.Component,

    properties: {
    },

    // use this for initialization
    onLoad: function () {


        var newSprite = new cc.Sprite("Texture/star-icon.png");
        this.addChild(newSprite); //Simulator: TypeError: this.addChild is not a function
        this.node.addChild(newSprite); //Black screen
        this.addComponent(newSprite); //Simulator: addComponent: The component to add must be a constructor
    },

    // called every frame
    update: function (dt) {

    },
});

Hi @C7an,

as far as I know, the only way to create a sprite is the following:

var node = new cc.Node("New Sprite");
var sprite = node.addComponent(cc.Sprite);
node.parent = this.node;

For further information see the engine-master\cocos2d\core\components\CCSprite.js file.

Best regards,
Zsolt

Hi, thanks for your reply.
But “New Sprite” is a name or filePath?
I can’t set texture like sprite.setTexture(“Texture/star-icon.png”);
It said “TypeError: sprite.setTexture is not a function”.

Do you mind if you give me some code how to add a image (path: “Texture/star-icon.png”) as a Sprite to the current Scene Compnonent (Helloworld.js)

//JS
cc.Sprite.create(“imagepath”);
someScene.addChild(sprite)

//C++
auto sprite = Sprite::create(“imagepath”);
someScene.addChild(sprite);

Many thanks :smiley:
Sorry, I’m so stupid :frowning:

Hi @C7an,

the “New Sprite” is the node name in the hierarchy. If you want to load the texture from file, use the following:

    var node = new cc.Node("New Sprite");
    var sprite = node.addComponent(cc.Sprite);
    node.parent = this.node;        

    var url = cc.url.raw("resources/image.png");
    var texture = cc.textureCache.addImage(url);
    sprite.spriteFrame = new cc.SpriteFrame(texture); 

I hope this helps.

Best regards,
Zsolt

1 Like

Oh thank you, that is all what I’m finding !!
You are the best!