user3390500 user3390500 - 1 month ago 12
Objective-C Question

Sprite Kit Modifying Attribute of a Child SKShapeNode Does Not Work

I have a class named Node,

Node is a subclass of SKNode,

I have created and added a SKShapeNode object as a child in the init method of the Node object,

But when i try to modify this child object after adding it as a child, nothing happens.

@interface Node ()
@property (nonatomic, strong) SKShapeNode *circle;
@end

@implementation Node

- (id)initWithRadius:(float)radius{

if (self = [super init]) {
_circle = [SKShapeNode shapeNodeWithCircleOfRadius:radius];
_circle.fillColor = [UIColor whiteColor];
_circle.name = @"c";
[self addChild:_circle];
}
return self;
}

//1st type of handling child object
- (void)setHighlighted{

NSLog(@"Called");
SKShapeNode *circ = (SKShapeNode *)[self childNodeWithName:@"/c"];
circ.fillColor = [SKColor redColor];
}


I also tried changing attribute of the property directly

- (void)setHighlighted{

_circle.fillColor = [SKColor redColor];
}


The setHighlighted method is being called for sure.

I even tried [_circle removeFromParent] and set position, alpha, isHidden attributes but nothing happens!!

What is the problem here?

Thanks

Answer

I suppose your problem is in the line:

SKShapeNode *circ = (SKShapeNode *)[self childNodeWithName:@"/c"];

that could be:

SKShapeNode *circ = (SKShapeNode *)[self childNodeWithName:@"//c"];

Differences according to API reference:

/ :

When placed at the start of the search string, this indicates that the search should be performed on the tree’s root node. When placed anywhere but the start of the search string, this indicates that the search should move to the node’s children.

// :

When placed at the start of the search string, this specifies that the search should begin at the root node and be performed recursively across the entire node tree. Otherwise, it performs a recursive search from its current position.

You could try to put also a breakpoint to the line below and check to the debug console the circ properties with po circ.debugDescription :

(breakpoint to the line:) -> circ.fillColor = [SKColor redColor];

You could try also to use a customActionWithDuration:

SKAction* circleColor = [SKAction customActionWithDuration:0.5f actionBlock:^(SKNode *node, CGFloat elapsedTime)
{
    circ.fillColor = [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f];
    NSLog(@"changed to red");
}];
[circ runAction:circleColor];
Comments