In my game scene I spawn balls from a ball class that move randomly with the MoveBy action.
I call this in my game scene:
Ball *ball = new Ball();
ball->spawnBall(this);
My question is, how do I release ball after the MoveTo action is over? If I call:
ball->release
Wouldn’t it delete the object before the action is over?
I want to have control of it’s memory (heap) because I found using the stack with automatic release:
Ball ball;
ball.spawnBall(this);
Some of the balls would stop randomly. I am thinking they are overwriting eachothers memory when spawned.
You might be after the RemoveSelf action. If you run a sequence as your action with the MoveTo action followed by a RemoveSelf action, then the node will be removed after the MoveTo action finishes.
If Ball is a type of Node then new Ball(); will create a retained object, i.e. a node with a retain count of 1.
If you are not adding ball to the autorelease pool, i.e. node->autorelease();, then you will need to release the object manually AFTER it has been added as a child. (Usually objects have a create function that automatically adds the node to the autorelease pool.)
Right so I don’t want to add it to the autorelease pool. I want control over it, and want to manually delete it after the action is over. Are you able to provide an example where I can do this given my code above?
//GameScene class
...
Ball *ball = new Ball(); //<----need to release this after action is over
ball->spawnBall(this);
...
//Ball class
...
void Ball::spawnBall(cocos2d::Layer *layer){
ball = Sprite::create();
layer->addChild(ball);
auto action = Sequence::create(MoveTo::create(...)), RemoveSelf::create(), null);
ball->runAction(action);
}
If you don’t need the Ball object anymore after spawnBall is called, then I recommend releasing it immediately after running the action on ball. Once the sprite is added to the layer, releasing the Ball object and removing it from memory will not affect the sprite.
But this seems like a waste of an object just to perform only one function. Would it not be better to add the spawnBall function to the GameScene class?
If the object will not always be released after calling spawnBall then that is fine. If the object will always be released after calling spawnBall then it’s best to put the release inside the function so you don’t forget to call it after calling spawnBall.
//GameScene class
...
Ball *ball = new Ball();
ball->spawnBall(this);
...
//Ball class
...
void Ball::spawnBall(cocos2d::Layer *layer){
ball = Sprite::create();
layer->addChild(ball);
auto action = Sequence::create(MoveTo::create(...)), RemoveSelf::create(), null);
ball->runAction(action);
release();
}