我有一个功能,可以保存场景中的所有节点,还有一个功能可以将它们添加回来(当应用程序打开时,这些功能可以很好地工作)。我遇到的问题是如何保存该数组,以便在应用程序重新打开时可以调用它。提前感谢您的帮助。
为我的节点添加了代码,以便更好地了解im试图实现的目标。
let bubble = SKShapeNode(circleOfRadius: self.frame.size.width / 12)
bubble.position = testBubble.position
bubble.fillColor = SKColor.black
bubble.strokeColor = SKColor.black
bubble.name = "bubble"
bubble.physicsBody = SKPhysicsBody(circleOfRadius: bubble.frame.height / 2)
bubble.zPosition = 2
let bubbleLabel = SKLabelNode(text: "Bubble")
bubbleLabel.fontColor = UIColor.darkGray
bubbleLabel.fontSize = 10
bubbleLabel.fontName = "MarkerFelt-Thin"
bubbleLabel.position.y = bubble.frame.size.width / 2 -bubble.frame.size.height / 1.65
bubbleLabel.zPosition = 3
self.addChild(bubble)
bubble.addChild(bubbleLabel)
@objc func saveAllNodes() {
nodeArray.removeAll()
for node in self.children {
nodeArray.append(node)
}
}
@objc func addAllNodes() {
self.removeAllChildren()
for node in nodeArray {
self.addChild(node)
}
}发布于 2018-01-28 01:01:23
您可能正在考虑使用CoreData或UserDefaults。当应用程序进入前台或者(可能更好)在你需要的任何地方的视图加载功能时,让节点加载到AppDelegate中。
您可以在NodeArrays中使用可转换项,并将其声明为@NSManaged var NodeArray
发布于 2018-01-28 05:50:35
不要费心使用CoreData或UserDefaults,SKNodes遵循NSCoding是有原因的,所以请使用KeyedArchiver。当你的应用关闭时,只需保存场景本身,当你的应用打开时,重新加载它。
注意,这是针对Swift 3的,不确定在使用Codable的Swift 4中有多大变化,但想法应该是相同的。
extension SKNode
{
func getDocumentsDirectory() -> URL
{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func save()
{
let fullPath = getDocumentsDirectory().appendingPathComponent(name)
let data = NSKeyedArchiver.archivedData(withRootObject: scene)
do
{
try data.write(to: fullPath)
}
catch
{
print("Couldn't write file")
}
}
static func load(name:String) -> SKNode?
{
let fullPath = SKScene.getDocumentsDirectory().appendingPathComponent(name)
guard let node = NSKeyedUnarchiver.unarchiveObject(withFile: fullPath.absoluteString) as? SKNode
else
{
return nil
}
return node
}
}然后使用它,当你需要保存你的场景时,只需在场景文件中调用save(),然后加载它,调用
guard let scene = SKNode.load("*myscenename*") as? SKScene
else
{
//error out somehow
}
view.presentScene(scene)要扩展NSCoding的常规功能,还需要实现编码和解码。这是在你自定义一些类并添加变量的时候使用的
要进行编码:
func encode(with coder:NSCoder)
{
coder.encode(variable, forKey:"*variable*")
}解码:
required init(coder decoder:NSCoder)
{
super.init(coder:decoder)
if let variable = decoder.decodeObject(forKey:"*variable*") as? VariableType
{
self.variable = variable
}
}https://stackoverflow.com/questions/48477947
复制相似问题