在Swift中将动态Int变量从一个类传递给另一个类 [英] Passing dynamic Int variable from one class to another class in Swift
问题描述
我有一个类GameScene里面我有一个公开的变量得分,并且不断更新更新功能。当两个节点相互碰撞时,我想发送得分值。一旦它碰撞,我使用mainview .presentScene( gameoverScene )语法去另一个场景。我想要在gameoverscene中更新的分数。
我尝试在gameoverscene中使用 private let _gameScene = GameScene(),并将其传递给一个使用 finalscore.text = String(_gameScene.finalScore)我得到的变量是我在开头宣布但不是更新的分数。请帮我找出解决方案。
我使用 NSUserDefaults
来处理这个。
所以,在 GameScene
之后的类 GameScene
被声明(而不是在任何函数中)使用
var score = Int()
var defaults = NSUserDefaults.standardUserDefaults()
然后在同一个类的 didMoveToView(view:SKView)
函数中,我使用
defaults.setInteger(0,forKey:score)
/ pre>
所以,当出现
GameScene
时,在开始游戏之前,当前得分将重置为0。
然后在碰撞函数中,在GameOver
场景即将被呈现之前(但仍然在GameScene
课程),您使用(在您的分数增加或减少后)defaults.setInteger(score,forKey:score )
这将设置当前的
分数
至中的
。分数
NSUserDefaults
最后,在
GameOver
场景中,在您提供分数之前,您可以说let scoreFromGameScene = NSUserDefaults.standardUserDefaults()。integerForKey(score)
label.text =\(scoreFromGameScene)//或任何你用来呈现分数的
这将确保您从
GameScene
获得当前分数,以便您可以在GameOver
场景中使用它。由于密钥score
将始终具有一个整数值,我们可以无错误地检索该值。
希望这有助于:)
Am new to swift 2 and i got stuck in passing a variable from one class to another.
I have a class "GameScene" in it I have a public variable score and it keeps updating in update function. I want to send the score value at the time when two nodes collide with each other. Once it collides I go to another scene using "mainview .presentScene(gameoverScene)" syntax. I want the updated score in gameoverscene.
I tried using "private let _gameScene = GameScene()" in gameoverscene and passing it to a lable using "finalscore.text = String( _gameScene.finalScore)" the variable what I get is O which I declared at the beginning but not the updated score. Pls help me in finding out the solution.
解决方案I used
NSUserDefaults
to handle this. So, in theGameScene
just after the classGameScene
is declared (and not in any function) I usedvar score = Int() var defaults = NSUserDefaults.standardUserDefaults()
Then in the
didMoveToView(view: SKView)
function in the same class, I useddefaults.setInteger(0, forKey:"score")
So that whenever
GameScene
is presented, the current score resets to 0 before you start the game. Then in your collision function, before theGameOver
scene is about to be presented (but still in theGameScene
class), you use (after your score has been increased or decreased)defaults.setInteger(score, forKey:"score")
This will set the current
score
to the key"score"
inNSUserDefaults
.Finally, in the
GameOver
scene, before you present the score, you can saylet scoreFromGameScene = NSUserDefaults.standardUserDefaults().integerForKey("score") label.text = "\(scoreFromGameScene)" //Or whatever you use to present the score
This will make sure that you get the current score from the
GameScene
so that you can use it in yourGameOver
scene. Since the key"score"
will always have SOME integer value, we can retrieve the value without error.Hope that helps :)
这篇关于在Swift中将动态Int变量从一个类传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!