I am having the same issue, see below the code which generates a green or red sprite. Attempting to give it the colour value within the SKSpriteNode.userData
. In my log output the userData
is (null)
!
+(SKSpriteNode *)randomSprite {
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"green.png"];
[sprite setUserData:[NSMutableDictionary dictionary]];
if ((arc4random() %(2)-1) == 0){
sprite = [SKSpriteNode spriteNodeWithImageNamed:@"green.png"];
[sprite.userData setValue:@"GREEN" forKey:@"COLOR"];
}else {
sprite = [SKSpriteNode spriteNodeWithImageNamed:@"red.png"];
[sprite.userData setValue:@"RED" forKey:@"COLOR"];
}
NSLog(@"user data = %@",sprite.userData);
sprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:sprite.size.width/2];
sprite.physicsBody.dynamic = YES;
return sprite;
}
For a workaround I guess we could create a reference dictionary where the SKSpriteNode
instances are the keys and a NSDictionary
of data are the values.
//----- * UPDATE ** -------
And theres no wonder, after the userData
was initialised, another sprite was being initialised in its place, leaving the userData
nil!
+(SKSpriteNode *)randomSprite {
SKSpriteNode *sprite;
if ((arc4random() %(2)-1) == 0){
sprite = [SKSpriteNode spriteNodeWithImageNamed:@"green.png"];
[sprite setUserData:[NSMutableDictionary dictionary]];
[sprite.userData setValue:@"GREEN" forKey:@"COLOR"];
}else {
sprite = [SKSpriteNode spriteNodeWithImageNamed:@"red.png"];
[sprite setUserData:[NSMutableDictionary dictionary]];
[sprite.userData setValue:@"RED" forKey:@"COLOR"];
}
NSLog(@"user data = %@",sprite.userData);
sprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:sprite.size.width/2];
sprite.physicsBody.dynamic = YES;
return sprite;
}