GameCorder.net

このエントリーをはてなブックマークに追加

control memory management about sprite in cocos2dx

coocs2dx is a c++.
so we have to controll memory management.
When I craete scene.
I use memory
And how I can control it?

create a class witch extends Layer
I hold this class member in a Scene
Player.hpp class is like this.

#ifndef Player_hpp
#define Player_hpp

#include 

class Player : public cocos2d::Sprite{
    Player();
    virtual ~Player();
public:
    // 生成メソッド
    static Player* create();
};

#endif /* Player_hpp */
		
		

Player.cpp is this

#include "Player.hpp"

// using name space
USING_NS_CC;

Player::Player()
{
}

Player::~Player()
{
}

Player* Player::create(){
    auto player = new Player();
    if(player && player->initWithFile("HelloWorld.png")){
        player->autorelease();
        return player;
    }
    CC_SAFE_DELETE(player);
    return nullptr;
}
		

and mainscene.
In this case HelloWorldScene.cpp

    // add Player
    {
    	// mPlayer is a member
        mPlayer = Player::create();
		// this will retain object + 1 in node
        this->addChild(mPlayer);
    }
		

In create method

    if(player && player->initWithFile("HelloWorld.png")){
    	// this sprite is auto released
        player->autorelease();
        return player;
    }		
		

player->autorelease();
this able to make auto release object.

In the mainScene.

// mPlayer is a member
mPlayer = Player::create();
// this will retain object + 1 in node
this->addChild(mPlayer);				
		

when add node object.
like objective-c reference count + 1
and before I comfirm autorelease so when this class not is refered.
This class is released and count - 1
like this we maintain memory in cocos2dx.