0

在啊我这样写

@interface A
{
  CCSprite *loadingSprite;
}

- (void)getTag;

@property (nonatomic, retain) CCSprite *loadingSprite;

@end

然后在实施中

@synthesize loadingSprite

- (id)init
{
 loadingSprite = [CCSprite spriteWithSpriteFrameName:@"loading-icon1.png"];
 [loadingSprite setTag:111];
 [self addChild:loadingSprite];
}

- (void)getTag
{
 NSLog(@"%@ tag %d",[loadingSprite getChildByTag:111] , [loadingSprite getChildByTag:111].tag)
}

在另一个类上,Bm 我写访问方法 getTag

A *a = [[A alloc] init];
[a getTag];

但不幸的是,getTag 中的 NSLog 显示:

(null) tag 0

如何从另一个类访问 ccsprite 的正确方法?谢谢

4

3 回答 3

2

查看我的教程“在场景层次结构中访问其他 Cocos2D 节点的策略”: http: //www.learn-cocos2d.com/2012/09/strategies-accessing-cocos2d-nodes-scene-hierarchy/

于 2012-12-14T12:53:01.850 回答
1

您正试图从精灵中按标签获取孩子。你想得到这个精灵。所以,如果你想使用getChildByTag:,使用

[self getChildByTag: tag];

代替

[yourSprite getChildByTag: tag];

当您将精灵添加到self. 您只能从其父级按标签获取子级。

哦,改变你的初始化方法。当您覆盖父级的初始化时,您应该首先调用父级的方法。

- (id) init
{
    self = [super init];

    if( self != nil )
    {
        // do your initialization here
    }

    return self
}
于 2012-12-14T07:38:49.533 回答
1

另一件事-您不必保留添加到类中的节点,因为 cocos2d 会在您使用时自动保留任何节点,[self addChild:node]并在您释放基本节点时释放,因此更好地使用@property (nonatomic, assign) CCSprite *loadingSprite;

您可以使用该属性从其他类访问节点 - 只需a.loadingSprite在您的示例中使用。毕竟,使用标签并不是访问节点的最佳解决方案,因为当您拥有大量节点和大量标签时,您可能很容易迷失在那里。

于 2012-12-14T12:53:51.773 回答