1
votes

How do you cast an sks file SKNode to a subclass of that node? Having the same issue as here where it says to set the custom class and the module in the sks editor, but that answer does not work!

I have constructed an assembly of SKSpriteNodes parented under an empty SKNode in the SpriteKit scene editor using the empty node as the root of the parts that make up the ship. The root SKNode.name is set to "ship" and the custom class field is set to "BasicShip" which is the class I am trying to cast to. The module is set to the project name (confirmed as the module name in the build settings.)

I am using the custom SKNode subclass to add dynamics to the ship, eg. thrust functions and the like.

Retrieving the node via childNodeWithName() returns a Optional(SKNode), not my custom class. Casting that returned node to my custom class compiles but crashes at runtime.

Examining the scene nodes in didMoveToView() shows the "ship" node as a generic SKNode as well so the custom class is not taking in the sks file, nor can it be cast to one at run time.

let world = self.childNodeWithName("world")
let ship = world!.childNodeWithName("ship") as! BasicShip
ship.thruster1.throttle = 0.5
ship.thruster2.throttle = 0.5

stops with the message: Could not cast value of type 'SKNode' (0x1001dcc60) to 'Lander001.BasicShip' (0x10000f2a0). My custom class is inheriting from SKNode, so the cast should not be a problem, right?

(xcode 7.2.1, osX 10.10 <- could it be an osX vs iOS thing? I want to run on both eventually.)

1
Been digging around in the scene and the nodes are where they should be so the question remains why would a known instance of an SKNode fail to cast to a subclass of that node? and does its origin being a .sks file have anything to do with it?rebusB
In sks file, did you set your ship as BasicShip custom class?Simone Pistecchia
Yes, and the Module as stated... To be clear though, setting it on the "ship" SKNode not the top level which I am assuming would be for setting a custom SKScene.rebusB

1 Answers

0
votes

I believe inside world there is another node having ship as name. And that is the one you are retrieving. Check you project and make sure you not adding another SKNode named ship to world.