所以我试图在名为PlayScene的类中的不同文件中引用一个名为high score的变量。我如何在我的GameScene.swift文件中引用该高分。这是我目前的GameScene.swift文件,但是在
行self.highscoreText.text = "Highscore: \(highscoreshow)
它说highscoreshow是一个未解析的标识符,因为我不知道如何从另一个类引用该变量
import SpriteKit
class GameScene: SKScene {
let playButton = SKSpriteNode(imageNamed:"play")
let title = SKSpriteNode(imageNamed: "title")
let highscoreText = SKLabelNode(fontNamed: "Chalkduster")
override func didMoveToView(view: SKView) {
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.title.position = CGPointMake(CGRectGetMaxX(self.frame) - 150
, CGRectGetMaxY(self.frame) - 150)
self.highscoreText.text = "Highscore: \(highscore)"
self.highscoreText.fontSize = 42
self.highscoreText.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) - 150)
self.addChild(self.playButton)
self.addChild(self.title)
self.addChild(self.highscoreText)
self.backgroundColor = UIColor(hex: 0x80D9FF)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.playButton {
var scene = PlayScene(size: self.size)
let skView = self.view as SKView
skView.ignoresSiblingOrder = true
scene.scaleMode = .ResizeFill
scene.size = skView.bounds.size
skView.presentScene(scene)
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
以下是创建和存储高分变量的另一个类中的函数:
func died() {
var defaults = NSUserDefaults()
var highscore = defaults.integerForKey("highscore")
if (score > highscore){
defaults.setInteger(score, forKey: "highscore")
}
var highscoreshow = defaults.integerForKey("highscore")
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
let skView = self.view as SKView
skView.ignoresSiblingOrder = true
scene.size = skView.bounds.size
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
答案 0 :(得分:1)
好的,有两个问题。
您可以使用NSUserDefaults在两个场景之间共享值highscoreshow
。
只需在方法顶部的GameScene中添加此行 didMoveToView
var highscoreshow = NSUserDefaults().integerForKey("highscore")
如果更改高分
,请记住更新NSUserDefaults中的值 NSUserDefaults().setInteger(highscoreshow, forKey: "highscore")
最后请注意,值NSUserDefaults保存在持久存储中。因此,如果您重新启动应用程序或设备,这些值仍然可用。
希望这会有所帮助。