我在我的游戏中有一个关卡场景,我在其中选择关卡。在这个场景中,我显示了在CCLabelTTF中选择的关卡。现在我想将此标签上显示的值传递给我的主场景。我这样做如下:将变量从一个场景传递到其他场景 - Cocos2D
HelloWorld *hello=[HelloWorld getInstance]; //HelloWorld is main scene
hello.strLevel=[lblLevel string]; //strLevel is NSString to which I am passing the label text
[[CCDirector sharedDirector]replaceScene:[HelloWorld node]];
在我的HelloWorld场景中,我使用singleton共享Level场景中使用的标签的值。
//HelloWorld.h
@interface HelloWorld : CCColorLayer
{
NSString *strLevel;
}
@property(nonAtomic,retain)NSString *strLevel;
+(HelloWorld*)getInstance;
HelloWorld.mm
@implementation HelloWorld
@synthesize strLevel;
static HelloWorld *instance=nil;
__________________________
//Some code
__________________________
+(HelloWorld*)getInstance
{
if(instance==nil)
{
instance=[HelloWorld new];
}
return instance;
}
然而,由于控制达到
instance=[HelloWorld new];
的init()被调用,这不是working.As很快。那么为何不。但是,当控件返回到传递值的行处的Level场景时,没有任何反应,并且HelloWorld显示strLevel的值为null。
我知道singleton是比AppDelegate传递值更好的方法。但我无法这样做。有人能纠正我吗?
谢谢
谢谢。这些都是非常棒的讨论。但我的问题在于在其他场景中使用单身。使用单身人士不会帮助我在两个场景之间分享价值。我知道我错了,但不知道在哪里。 – Nitish 2011-04-14 06:13:04
你可以从程序中的任何地方调用你的单例对象,因为它是静态的,就像这样[[MySingleton sharedInstance] myMethod]; sharedInstance是一个类函数,看起来像这样+(MySingleton *)sharedInstance,它返回一个ptr到静态分配的类MySingleton *的对象。 myMethod是一个实例方法。诀窍是单身人士一直活到终止程序。除非你认为必要,否则你不应该释放它。你也不必分配/初始化你的单例,因为它只在sharedInstance调用中完成一次。 CCDirector也是单身人士。 – 2011-04-14 06:25:51
我不会将我的场景定义为singelton,因为场景变化很快。你会被困在内存中的所有场景。而是在您存储数据的地方构建一个sharedData类。我认为这是你的问题所在[[CCDirector sharedDirector] replaceScene:[HelloWorld node]];因为调用节点实际上是返回HelloWorld场景的一个新的自动释放实例。 – 2011-04-14 06:38:13