Hello. I want to add a leaderboard to my android game. I’ve created one in google play console successfully. I’ve used three scripts for managing score, leaderbooards and game/player:
-
LeaderBoardManagerScript where I manage everything related to leaderboards (login, add score and show leaderboard.
-
ScoreScript, where I manage everything related to score system
-
Player script, where I manage player and game behavior.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using UnityEngine.UI;public class LeaderboardManagerScript : MonoBehaviour
{
public int score;
public static LeaderboardManagerScript current;private void Awake() { if (current == null) current = this; } // Start is called before the first frame update void Start() { PlayGamesPlatform.Activate(); Login(); } // Update is called once per frame void Update() { } public void Login() { Social.localUser.Authenticate((bool success) => { }); } public void AddScore() { Social.ReportScore(ScoreScript.current.score, Leaderboard.leaderboard_best_scores, (bool success) => { }); } public void ShowLeaderboard() { if (Social.localUser.authenticated) { PlayGamesPlatform.Instance.ShowLeaderboardUI(Leaderboard.leaderboard_best_scores); } else { Login(); } }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class ScoreScript : MonoBehaviour
{
public int score;
public Text scoreText;
public Text highScoreText;public static ScoreScript current; private void Awake() { if (current == null) current = this; } void Start() { score = 0; } void Update() { scoreText.text = score.ToString(); } private void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Score") { score++; PlayerScript.current.playerSpeed = PlayerScript.current.playerSpeed + 3; } if (other.gameObject.tag == "Score2") { score += 2; PlayerScript.current.playerSpeed = PlayerScript.current.playerSpeed + 3; } if (other.gameObject.tag == "Jackpot") { score += 5; PlayerScript.current.playerSpeed = PlayerScript.current.playerSpeed + 5; } } public void CheckHighScore() { if (PlayerPrefs.HasKey("highScore")) { if (score > PlayerPrefs.GetInt("highScore")) PlayerPrefs.SetInt("highScore", score); } else PlayerPrefs.SetInt("highScore", score); highScoreText.text = PlayerPrefs.GetInt("highScore").ToString(); }
}
I’ve created a button in canvas for leaderboard, set the onclick event to playerScript where I put the following void
public void ShowLeaderboard()
{
LeaderboardManagerScript.current.ShowLeaderboard();
}
when I run the game, if I push the Leaderboard button, I get a null reference exception. Not sure why, so I’m asking help…