You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift:如何从GameScene向ViewController传递高分变量?高分显示为0怎么办

解决GameCenter高分显示为0的问题

Hey there, let's work through why you're only seeing 0 when trying to send your GameScene's highscore to Game Center. Here are the key fixes to try out:

  • 确认GameScene引用是否正确
    A common issue is that self.gameScene might not be pointing to the active, running instance of your GameScene. If you're using a Storyboard to set up your SKView, make sure you properly capture the scene reference in your GameViewController:

    override func viewDidLoad() {
        super.viewDidLoad()
        // 确保view是SKView,并且场景已经加载为GameScene
        guard let skView = self.view as? SKView,
              let loadedGameScene = skView.scene as? GameScene else {
            print("Failed to get reference to GameScene")
            return
        }
        self.gameScene = loadedGameScene
    }
    

    If your GameScene loads later (like after the user starts a game), self.gameScene might still be an uninitialized instance when you tap the GameCenter button—leading to that default 0 value.

  • 验证GameScene中highscore是否被正确更新
    仔细检查GameScene里的highscore变量在游戏过程中是否被正确赋值,别忘了持久化存储它,避免场景重载后数据丢失:

    // 在GameScene的得分更新逻辑中
    func updateScore(newScore: Int) {
        if newScore > highscore {
            highscore = newScore
            // 保存到UserDefaults,方便后续可靠读取
            UserDefaults.standard.set(highscore, forKey: "PlayerHighScore")
        }
    }
    

    如果highscore只在游戏结束时计算,要确保这个计算在你点击GameCenter按钮前已经完成。

  • 通过UserDefaults读取高分(比场景引用更可靠)
    依赖场景引用可能会因为场景销毁或重初始化失效,不如在GameViewController的按钮点击事件里直接从UserDefaults获取保存的高分:

    @IBAction func gameCenterButtonTapped(_ sender: UIButton) {
        let savedHighScore = UserDefaults.standard.integer(forKey: "PlayerHighScore")
        // 如果没有保存过的高分,再回退到场景中的highscore
        let scoreToSubmit = savedHighScore != 0 ? savedHighScore : (self.gameScene?.highscore ?? 0)
        saveHighScore(number: scoreToSubmit)
    }
    

    这样即使GameScene的引用出问题,你也能拿到最后保存的真实高分。

  • 检查saveHighScore函数的实现
    确保你的saveHighScore函数正确处理了GameCenter认证和分数提交流程。如果用户未登录,分数根本无法提交,排行榜自然会显示0:

    func saveHighScore(number: Int) {
        guard GKLocalPlayer.local.isAuthenticated else {
            // 提示用户登录GameCenter
            GKLocalPlayer.local.authenticateHandler = { [weak self] viewController, error in
                guard let self = self else { return }
                if let loginVC = viewController {
                    self.present(loginVC, animated: true)
                } else if GKLocalPlayer.local.isAuthenticated {
                    // 登录成功后重新提交分数
                    self.saveHighScore(number: number)
                }
            }
            return
        }
        
        let score = GKScore(leaderboardIdentifier: "YOUR_LEADERBOARD_ID")
        score.value = Int64(number)
        
        GKScore.report([score]) { error in
            if let error = error {
                print("Failed to submit score: \(error.localizedDescription)")
            } else {
                print("Highscore submitted successfully!")
            }
        }
    }
    

    还要确认代码里的排行榜ID和你在苹果开发者后台配置的完全一致——拼写错误是常见的问题根源。

  • 验证GameCenter排行榜的配置
    确保你在苹果开发者控制台正确创建了排行榜,ID匹配无误,并且应用的Bundle ID和注册信息一致。如果排行榜关联不正确,分数提交会失败,排行榜就会显示默认的0分。

内容的提问来源于stack exchange,提问作者Tom Sanchez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:21:58