gpt4 book ai didi

swift - 如何从 GameViewController 更新 SKScene 中的变量?

转载 作者:行者123 更新时间:2023-11-28 10:08:49 24 4
gpt4 key购买 nike

我已将 admob 奖励视频添加到我的应用中。 admob 一切正常。但是,我无法在观看奖励视频后更新直播标签。如果我去另一个场景然后回来,它会更新并显示新值。

//GameViewController.swift

 func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
didRewardUserWith reward: GADAdReward) {
print("Reward received with currency: \(reward.type), amount \(reward.amount).")


GameData.shared.lives = GameData.shared.lives + 1
UserDefaults.standard.set(GameData.shared.lives, forKey: "lives")
UserDefaults.standard.synchronize()
}

//主场景.swift

var lives = UserDefaults.standard.integer(forKey: "lives") {
didSet{
livesLabel?.text = "\(lives)"
}
}

//

最佳答案

我个人的建议是通过计算属性与场景建立联系:

class ViewController : UIViewController
{
var mainScene : MainScene? { return (self.view as SKView?).scene as? MainScene}
var lives : Int
{
get
{
return mainScene?.lives ?? 0
}
set
{
mainScene?.lives = newValue
//perhaps do some error handling if mainscne is nil
}
}
}

然后在你的主场景中,你控制 lives 如何写入 userdefaults

class MainScene : SKScene
{
private var _lives : Int?
var lives : Int
{
get
{
_lives = _lives ?? UserDefaults.standard.integer(forKey: "lives")
return _lives!
}
set
{
_lives = newValue
UserDefaults.standard.set(_lives, forKey: "lives")
UserDefaults.standard.synchronize()
livesLabel?.text = "\(_lives)"
}
}
}

最后要使用它,你会做:

 func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
didRewardUserWith reward: GADAdReward) {
print("Reward received with currency: \(reward.type), amount \(reward.amount).")

lives += 1
}

这样我们就可以避免处理全局变量,这意味着出现错误和错误的机会更少

关于swift - 如何从 GameViewController 更新 SKScene 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50330800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com