GameViewController 中的 unarchiveFromFile 方法是做什么用的? [英] What is the method unarchiveFromFile in GameViewController for?

查看:43
本文介绍了GameViewController 中的 unarchiveFromFile 方法是做什么用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 Swift 中为我的游戏添加不同的场景时,我遇到了 unarchiveFromFile 方法.这种方法的问题在于它只适用于 GameScene 类.如果你从

When I tried to add different scenes to my game in Swift, I encountered the method unarchiveFromFile. The problem with this method is that it only works with the GameScene class. If you call it from

extension SKNode {
    class func unarchiveFromFile(file : NSString) -> SKNode? {
        if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
            var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
            var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)

            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene 
            archiver.finishDecoding()
            return scene
        } else {
            return nil
        }
    }
}

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
             let skView = self.view as SKView
             skView.ignoresSiblingOrder = true
             skView.presentScene(scene)
        }
        // This won't work for MenuScene.unarchiveFromFile("MenuScene") as? MenuScene
        // nor MenuScene.unarchiveFromFile("MenuScene") as? GameScene

为了能够与其他 SKScene 一起工作,我将所有出现的类 GameScene 更改为 SKScene.虽然它现在适用于其他 SKScene 类,但我仍然不明白它是什么.

To be able to work with other SKScenes I changed all occurrences of the class GameScene to SKScene. While it now works with other SKScene classes I still don't understand what it is.

这个方法有什么用?我应该保留它吗?

What is it this method for? should I keep it?

推荐答案

我对 Xcode 6 的使用不多,但这是我的理解(有人可以纠正我或阐述):

I haven't used Xcode 6 much, but here is my understanding (someone may correct me or expound) :

这就是您的应用如何利用 GameScene(或任何 SKScene)的布局数据等.如果您单击 Project Navigator 面板中的 GameScene.sks 文件,您将获得一个用于您的 GameScene 的可视化编辑器.

This is how your app utilizes the layout data etc for the GameScene (or any SKScene). If you click on the GameScene.sks file in the Project Navigator panel you get a visual editor for your GameScene.

如果您希望使用此布局数据,您可以使用该方法.您可以在场景编辑器中直观地布置您的 GameScene,而无需对位置、设置等进行编码.

If you want this layout data to be utilized, you would use that method. You can visually layout your GameScene in the scene editor without need to code locations, settings etc.

这篇关于GameViewController 中的 unarchiveFromFile 方法是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆