I'm a noob, so, forgive me if this is a very basic question. I'm creating my first app and it's a game. The code became too large for one file (is annoying to go up and down all the time). So I put my functions at other file. The problem is that addChild do not work from other file. In my game, when a player stops at a specific place, an Node must be called. If the function is at the "GameScene.swift" file it works perfectly, but if the function is at any other swift file, the Node is called, but is not shown. I know the the object was called because if the player hits the same place a second time the game crashes with a message saying that I'm trying to cast a object that is already casted.
The Node I want to call is placed inside a Struct, so is accessible from any part of my code.
There is a proper way to cast a node from other file?
An example to make it clear. The bellow code works nicely. I touch the square and other square appears
// GameScene.swift // teste1 import SpriteKit struct myStruct { static let myNode : SKShapeNode = SKShapeNode(rectOfSize: (CGSizeMake(100,100)), cornerRadius: 5) static let myGameScene = GameScene() } class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ myStruct.myNode.position = CGPoint(x:(CGRectGetMidX(self.frame)), y:(CGRectGetMidY(self.frame)) + 150) myStruct.myNode.fillColor = SKColor.redColor() let button : SKShapeNode = SKShapeNode(rectOfSize: (CGSizeMake(100,100)), cornerRadius: 5) button.position = CGPoint(x:(CGRectGetMidX(self.frame)), y:(CGRectGetMidY(self.frame))) button.fillColor = SKColor.greenColor() button.name = "button" addChild(button) } // end DidMoveToView func addNode () { addChild(myStruct.myNode) } override func touchesBegan(touches: Set, withEvent event: UIEvent?) { let touch = touches //as! Set let location = touch.first!.locationInNode(self) let node = self.nodeAtPoint(location) // +++ BUTTON: DICE +++ if (node.name == "button") { addNode() } } } //end GameScene
But is not possible do the same from other file. Let's say I transfer the function addNode () to other swift file like this:
// otherFile.swift // teste1 import SpriteKit func addNode () { myStruct.myGameScene.addChild(myStruct.myNode) }
When I touch the "button" noting happens, but if I touch a second time:
2016-01-17 09:54:54.641 teste1[954:24089] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: name:'(null)' accumulatedFrame:{{460.64999, 482.64999}, {102.7, 102.7}}' *** First throw call stack: