Search code examples
javaandroidjava-native-interfacecocos2d-x

How to replace cocos2d-x scene from Java?


I want to replace the scene in a cocos2d project from Java. I created the following JNI methods:

void cocos_android_app_init (JNIEnv* env, jobject thiz) {
    LOGD("cocos_android_app_init");
    AppDelegate *pAppDelegate = new AppDelegate();
}

extern "C" {
    JNIEXPORT void JNICALL Java_com_example_myapp_MainActivity_changeScene( 
        JNIEnv* env, jobject thiz){
            cocos2d::Scene* scene = MyScene::createScene();
            Director::getInstance()->replaceScene(
                 TransitionFade::create( 1, scene ));
            //NOT WORKING BECAUSE Director::getInstance() is NULL
}
}

However, when the method changeScene is called from java, my App crashes because Director::getInstance() seems to be a NULL-pointer. How can the scene be changed correctly from Java?


Solution

  • I tried this :

    extern "C"
    {
        void Java_org_cocos2dx_cpp_SceneChanger_nativeCallbackChangeScene(JNIEnv*  env, jobject thiz)
        {
            Director::getInstance()->replaceScene(MyScene::createScene());
        }
    };
    

    and it replaces the scene successfully.

    Are you sure Director::getInstance() is a null pointer ?

    Make sure that you are running on OpenGL thread.

    Check your error log, look for a line saying call to OpenGL ES API with no current context which means you are not running on gl thread.

    To run on gl thread use this code :

    Director::getInstance()->getScheduler()->performFunctionInCocosThread([&](){
        Director::getInstance()->replaceScene(MyScene::createScene());
    });