Cocos2d 断言失败:引用计数应大于 0

Cocos2d Assert failed: reference count should be greater than 0

我正在尝试使用 touchBegan 在另一个节点中添加一个 public 节点,但我通过控制台收到此错误

Assert failed: reference count should be greater than 0
Assertion failed: (_referenceCount > 0), function retain, file /Users/user/Desktop/App/cocos2d/cocos/base/CCRef.cpp, line 93.

这是我的代码:

.h

cocos2d::Node* node1 = cocos2d::Node::create();
cocos2d::Node* node2 = cocos2d::Node::create();

.ccp

bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
 node1->removeAllChildren();
 node1->addChild(node2);
return true
}

您正在 .h 文件中创建节点?那是行不通的。在初始化函数中执行:

bool HelloWorld::init()
{
    if (!Layer::init())
    {
        return false;
    }

    auto node1 = Node::create();
    auto node2 = Node::create();
}

.h

class HelloWorld
{
...

Node *node1;
Node *node2;
}

.cpp

bool HelloWorld::init()
{
    if (!Layer::init())
    {
        return false;
    }

   node1 = Node::create();
   addChild(node1);
}

bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
 node1->removeAllChildren();
 node2 = Node::create();
 node1->addChild(node2);
return true
}