Swift,SpriteKit:如何保存场景的整个进度 [英] Swift, SpriteKit: how to save the whole progress of a scene

查看:202
本文介绍了Swift,SpriteKit:如何保存场景的整个进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用GameViewController.swift建立一个快速游戏

I have build a swift game with a "GameViewController.swift"

import UIKit
import SpriteKit

class GameViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()


    if let scene = GameScene(fileNamed:"GameScene") {
        // Configure the view.
        let skView = self.view as! SKView

        /* Set the scale mode to scale to fit the window */


        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
        }
    }
}

和我有一个名为GameScene的场景(当你打开swift并创建一个新的快速游戏时,它是默认的游戏文件)

and i have a scene called "GameScene"(it is the default game-file when you open swift and create a new swift game)

import UIKit
import SpriteKit

class GameScene: SKScene{

var building = SKSpriteNode()

override func didMoveToView(view: SKView) {

    /* Setup your scene here */

}

那里发生了很多事情。 (可以放置建筑物并触发一些动作等等)

但是当你离开应用程序时,所有进度都会丢失。

如何保存这个GameScene的全部进度并在开始时重装?

a lot of things going on there. (buildings can be placed and that trigger some actions and so on)
But all the progress is lost when you leave the app.
How to save the whole progress of this "GameScene" and reload it at the start?

推荐答案

SKScene符合NSCoding,因此您可以使用它来存档您的场景。这是一个可能有用的教程。 https://www.hackingwithswift.com/read/12/ 3 / fix-project-10-nscoding

SKScene conforms to NSCoding, so you can use this to archive your scene. Here is a tutorial that may help. https://www.hackingwithswift.com/read/12/3/fixing-project-10-nscoding

基本的想法是你拍摄场景的实例,并将其存档:

The basic idea is you take the instance of your scene, and you archive it with:

NSKeyedArchiver.archivedData(withRootObject:scene)

然后拿这个并将其保存到磁盘或其他地方

Then take this and save it to disk or somewhere else

然后您可以使用

NSKeyedUnarchiver.unarchiveObject(with:scene)as! SKScene

现在,当您创建自定义场景类时,您需要确保包含您需要保存的任何变量。这是令人讨厌的所需的init(编码器aDecoder:NSCoder)初始化器,人们往往不会使用。

Now when you make a custom scene class, you need to be sure to include any variables you create that you need to save. This is where that pesky required init(coder aDecoder:NSCoder) initializer comes in that people tend to not use.

您基本上使用此初始值设定项来解码您的自定义变量,如下所示。

You basically use this initializer to decode your custom variables, like this.

required init(coder aDecoder: NSCoder) {
    player = aDecoder.decodeObject(forKey: "player") as! String
}

要将其保存到存档,请添加编码方法

To save it to the archive, you add an encode method

func encode(with aCoder: NSCoder) {
    aCoder.encode(player, forKey: "player")
}

这篇关于Swift,SpriteKit:如何保存场景的整个进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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