简体   繁体   中英

How to add a sprite from another .swift file?

I have a project I've been working on for some time. I am using Sprite-Kit but now want to be able to add a child node from a swift file that is different from the GameScene.swift file.

Some of main code from the view controller that loads the GameScene is shown here:

let skView:SKView = SKView()
let theScene:SKScene = SKScene()

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if let theScene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsFPS = true
            skView.showsNodeCount = true

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true

            /* Set the scale mode to scale to fit the window */
            theScene.scaleMode = .ResizeFill  //.AspectFill
            var customSceneSize = CGSizeMake(2560, 1600)
            theScene.size = customSceneSize
            skView.presentScene(theScene)
            makeFakeStuff() // prepares some sample data
        }
    }

Usually I add sprites in the GameScene.swift file using "self.addChild". That won't work from another .swift file, so I have tried:

theScene.addChild(flyingCell)

and I tried:

skView.scene?.addChild(flyingCell)

These execute without error, but nothing shows on the screen. When I try to otherwise use the identical sprite code and put it in the GameScene.swift file and use "self.addChild" it draws it, so the sprite code (not shown) seems fine (position, zPosition, etc). I also made "flyingCell" a global variable to see if that would help ... nope. Any ideas?

I had 2 things wrong in my code.

The first is visible in my question: I should have declared "theScene" using "var" and not "let"

The second problem was in my gamescene, I needed to put "theScene = self"

Apple DTS helped me solve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM