Node created programmatically not rendered

Hello,
I am using Cocos Creator 2.0.2 on Windows 7.
I want to programmatically create a new node with a label and a sprite components.

Here is what I am doing

class MyChildNodeType extends cc.Node {
    private titleLabel: cc.Label;
    private backgroundSprite: cc.Sprite;
    constructor(text, spriteFrame) {
        super();
        this.width = 100;
        this.height = 100;
        this.color = cc.Color.BLACK;
        this.titleLabel = this.addComponent(cc.Label);
        this.titleLabel.string = text;
        this.backgroundSprite = this.addComponent(cc.Sprite);
        this.backgroundSprite.spriteFrame = spriteFrame;
    }
    onLoad() {
        console.log("load activity block!");
    }
    update() {
        console.log("update activity block!");
    }
}



class MyParentNodeType extends cc.Node {

    //...

    rebuildChildren() {
        const myNewNode = new MyChildNodeType("hey", mySpriteFrame);
        myNewNode.setPosition(0, 0);
        this.node.addChild(myNewNode, this.node.zIndex + 10000);
    }
}

When debugging, the node seem to have been instanciated, and the values inside it look ok.
However, when running it, I see nothing.
It never breaks on breakpoints at myNewNode.onLoad() and myNewNode.update(). So I think we can safely assume that this node is never loaded or updated.

Is there something I missed?

I’ve seen that there are both a parentNode.addChild(childNode) and a childNode.setParent(parentNode) methods. Using both at the same time fails with an “Node already added!” error. So I believe they do the same thing?

Thank you for any help :slight_smile:

I kind of solved my problem.
Inside the child node, the label was not shown because hidden by the sprite. But the sprite is not rendered (for a still unknown reason), but still wipes out the label.
If I disable the sprite, the label is shown correctly.
Now, even with the label rendered, the onLoad() and update() methods of the child node are never called. What is the trick to make then called? Of course I could make the parent node call them. But the game loop seem to call all update() of all nodes automatically. How can I automate that? I tried adding @ccclass, without success. I dont exactly understand what is the effect of @ccclass. Is it only to be able to add @property ?

Ok I’m learning a lesson here. You cannot add both a cc.Label and cc.sprite to a unique cc.Node, because they both want to hog the render attributes (e.g. myNode.color). Therefore the right way is to instantiate one sub-node for each label and sprite.
I still dont know why update and onLoad are not called.

Ok I finally solved it.
I was instantiating a cc.Node, but nodes dont have update() or onLoad() method. Only cc.Component does.