How to addChild when a UI Button is clicked/TOUCHED

Cocos2d-JS v3
  • efares
    Likes 0

    Problem Description

    I am making a UI Button like this

    // Instructions Button
            var instructionsButton = new ccui.Button();
            instructionsButton.loadTextures("instructions_n.png", "instructions_s.png", "", ccui.Widget.PLIST_TEXTURE);
            instructionsButton.setTouchEnabled(true);
            instructionsButton.addTouchEventListener(this.onInstruction, this);
            instructionsButton.setPosition(cc.p(x, y));
            this.addChild(instructionsButton);

    And adding an image that contains some instructions like this

    // Instructions Page
            this.instructionsPage = new ccui.Button();
            this.instructionsPage.loadTextures(res.instructions_png, res.instructions_png);
            this.instructionsPage.setTouchEnabled(true);
            this.instructionsPage.addTouchEventListener(this.onCloseInstructions, this);
            this.instructionsPage.setPosition(cc.p(x, y));

    And I only want to show the Instruction Page (add it as a child) when the UI Button is touched so I did this

    // Instruction button is selected
        onInstruction: function (sender, type) {
            switch (type) {
            case ccui.Widget.TOUCH_BEGAN:
                break;
            case ccui.Widget.TOUCH_MOVED:
                break;
            case ccui.Widget.TOUCH_ENDED:
                this.addChild(this.instructionsPage);
                break;
            case ccui.Widget.TOUCH_CANCELLED:
                break;
            }
        }

    This works fine when I test it on my laptop browser but the instructionsPage does not show when I run it on my Android device.
    I am using Cocos2d-x JS v3.7 on a Mac and testing on Chrome browser.


  • Sonar Systems admin
    Likes 0

    What happens on your Android device.

  • efares
    Likes 0

    Nothing happens when I click the instructions UI button, the layer is not added.

  • Sonar Systems admin
    Likes 0

    Do you get any logs.

  • efares
    Likes 0

    I’m not exactly sure how to collect logs from my android device, I can search online and see how.

  • efares
    Likes 0

    I ran my code in xCode and got this error:

    jsb: ERROR: File /Users/jenkins/Work/CocosPackageAuto/CocosFramework/cocos2d-x/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp: Line: 1479, Function: js_cocos2dx_Node_addChild
    Invalid Native Object

    I don’t know what this error message means, I am a beginner when it comes to JSB.

  • Sonar Systems admin
    Likes 0

    Is this error on a fresh project?


  • efares
    Likes 0

    Hey the problem is solved! I used

    instructionsPage.retain();

    And it did the trick. Works perfectly fine on my Android device now smiley


    This reply has been verified.
  • Sonar Systems admin
    Likes 0

    Great to hear, feel free to ask any other questions you have.

Login to reply