动作后释放新对象

Release new object after action

本文关键字:对象 新对象 释放      更新时间:2023-10-16

在我的游戏场景中,我从一个随MoveBy动作随机移动的球类中生成球。我的问题是,如何在MoveTo动作结束后释放球?请看下面的代码:

//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(MoveBy::create(...)), RemoveSelf::create(),   null);
ball->runAction(action);
}

我想控制它的内存(堆),因为我发现使用自动释放(堆栈):

  Ball ball;
  ball.spawnBall(this);

一些球会随机停止。我认为它们在生成时覆盖了彼此的内存。

谢谢

您的问题似乎是,如果runAction是异步调用,您的堆栈变量将超出范围:

int GameScene::func()
{
 Ball ball;
 ball.spawnBall(this); 
 return 0; //ball is automatically deleted here
}

你应该能够

int GameScene::func()
{
 Ball *ball = Ball::create(); //dont use new here, use create() function here and autorelease
 ball.spawnBall(this); 
 //autorelease here
 return 0;
}

我强烈推荐阅读Cocos2d-x中的内存释放