Load SpriteKit levels from filename

最后都变了- 提交于 2019-12-04 13:01:39

This can be done using NSClassFromString:

For Swift 2:

extension SKScene {
    static func sceneWithClassNamed(className: String, fileNamed fileName: String) -> SKScene? {
        guard let SceneClass = NSClassFromString("Your_App_Name.\(className)") as? SKScene.Type,
              let scene = SceneClass.init(fileNamed: fileName) else { 
            return nil 
        }

        return scene
    }
}

Or Swift 1:

extension SKScene {
    static func sceneWithClassNamed(className: String, fileNamed fileName: String) -> SKScene? {
        if let SceneClass = NSClassFromString("Your_App_Name.\(className)") as? SKScene.Type,
           let scene = SceneClass(fileNamed: fileName) {
            return scene
        }

        return nil
    }
}

Usage:

if let scene = SKScene.sceneWithClassNamed("MyScene", fileNamed: "MyScene") {
    view.presentScene(scene)
}

Its important to note that for this to work correctly your SKScene subclass must implement init(coder aDecoder: NSCoder), for example:

required init?(coder aDecoder: NSCoder) {
    // ...
    super.init(coder: aDecoder)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!