Thursday, November 19, 2015

Access to SKReferenceNode in iOS 9 in the Code

SKReferenceNodes were introduced in iOS 9.  This lets you separate items of you game into different sks files so you can reuse them.  For example if you had a game with several scenes that used a ball in most of the scenes, you could create a ball.sks file with the ball and reuse that ball in each scene.

The problem I was having was retrieving this ball in code.  Most discussions I found said you could just reference that node by the name and that's it.  What they did not mention is you get a SKReferenceNode which contains an array of the scenes which then contains the node you're looking for.

Example:
In my GameScene.sks file I have a reference node named "ballRef".  "ballRef" is a reference to the file ball.sks.  ball.sks has one SKSpriteNode in it named "ball".  Ball is a subclass of SKSpriteNode and is set as the Custom Class in the ball.sks file.  In GameScene.m (sorry, still using obj-c), I retrieved the ball node by doing the following:


    SKReferenceNode* ballRef = (SKReferenceNode*)[self childNodeWithName:@"ballRef"];
    for( SKNode* node in [ballRef.children lastObject].children ) {
        if ( [node.name isEqualToString:@"ball"] ) {
            Ball* ball = (Ball*)node;
        }

    }

  Not sure if it's correct, but nothing else worked for me.  

No comments:

Post a Comment