谷歌排行榜接入

您所在的位置:网站首页 谷歌热门游戏排行榜 谷歌排行榜接入

谷歌排行榜接入

2023-07-14 18:27| 来源: 网络整理| 查看: 265

谷歌排行榜看了很多教程,大部分人只提了重点的:初始化,提交分数,显示排行榜的几个方法,很少有完整的可以直接导入项目直接使用的。 既然我已经做好,并且项目需要整理技术文档,索性就搞一篇文章 废话不说 安卓篇后续补IOS 一,环境配置部分。 1,GooglePlayServices接入下载地址 2,导入下载的.Unitypage插件进Unity。 在这里插入图片描述 有导入插件经验的就知道有时候会报错,问题不大,都好解决 有这两个主文件夹就行 在这里插入图片描述 3,配置谷歌服务。 谷歌游戏服务不支持ios,0.9.50完全移除ios配置。 在unity中Windows下面这个位置。 在这里插入图片描述 打开以后是这样的 按下面的图去配置 在这里插入图片描述 把你得googleplay上配置的排行文件 和web app client id填入对应位置。 配置文件申请不再赘述,需要注册谷歌开发者账号25$,教程地址 然后点击Setup。 得到以下提示就Ok了。 在这里插入图片描述

下面脚本直接全选复制创建一个Leaderboard名字的C#脚本用的时候先 Leaderboard.Instance.Init();然后就可以用单例调用了,代码里的注释写的很完整,不会的仔细看注释

using System; using UnityEngine; using UnityEngine.SocialPlatforms; using System.Collections.Generic; using GooglePlayGames; using GooglePlayGames.BasicApi; #if UNITY_ANDROID && GOOGLE_PLAY using GooglePlayGames; using GooglePlayGames.BasicApi; #endif /* * android SetUp下把导出的xml粘贴进去 clienId 填进去 排行ID是xml中的一串英文 登录失败情况 1.deveError 检查clienId 2.Canceled 检查后台配置 重启unity */ public class Leaderboard : MonoSingleton { private void Awake() { #if UNITY_ANDROID && GOOGLE_PLAY try { if (Application.internetReachability == NetworkReachability.NotReachable) { return; } PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder() // requests an ID token be generated. This OAuth token can be used to // identify the player to other services such as Firebase. // //启用保存游戏进度的功能。 // .EnableSavedGames() //请求播放器的电子邮件地址可用。//将提示您同意。 //.RequestEmail() //请求生成服务器身份验证代码,以便可以将其传递到 // 相关联的后端服务器应用程序,并交换为OAuth令牌。 //.RequestServerAuthCode(false) //请求生成ID令牌。此OAuth令牌可用于 // 将玩家标识为其他服务,例如Firebase。 // .RequestIdToken() .Build(); PlayGamesPlatform.InitializeInstance(config); // 查看Google服务输出信息 recommended for debugging: // PlayGamesPlatform.DebugLogEnabled = false; // Activate the Google Play Games platform //激活谷歌服务 PlayGamesPlatform.Activate(); //判断用户是否登录 SignIn(); } catch (Exception e) { Debug.Log(e.ToString()); } #endif } void SignIn() { // 认证用户,判定用户是否登录: #if UNITY_EDITOR m_IsLogin=true; #else DoLogin(null); #endif } bool m_IsLogin = false; private void DoLogin(Action callback) { //if (m_IsLogin) //{ // if (callback != null) // callback(true); // return; //} Action DidSocialLogin = (bool success) => { if (success) { Debug.Log("Authentication successful"); string userInfo = "Username: " + Social.localUser.userName + "\nUser ID: " + Social.localUser.id + "\nIsUnderage: " + Social.localUser.underage; Debug.Log(userInfo); m_IsLogin = true; #if UNITY_ANDROID && GOOGLE_PLAY ((GooglePlayGames.PlayGamesPlatform)Social.Active).SetGravityForPopups(Gravity.BOTTOM); #endif if (callback != null) callback(success); } else { m_IsLogin = false; Debug.Log("Authentication failed"); } }; try { Action DidSocialLogin1 = (SignInStatus success) => { Debug.LogError("unity load:"+ success); switch (success) { case SignInStatus.Success: Debug.Log("Authentication successful"); string userInfo = "Username: " + Social.localUser.userName + "\nUser ID: " + Social.localUser.id + "\nIsUnderage: " + Social.localUser.underage; Debug.Log(userInfo); m_IsLogin = true; #if UNITY_ANDROID && GOOGLE_PLAY ((GooglePlayGames.PlayGamesPlatform)Social.Active).SetGravityForPopups(Gravity.BOTTOM); #endif if (callback != null) callback(true); break; case SignInStatus.UiSignInRequired: break; case SignInStatus.DeveloperError: break; case SignInStatus.NetworkError: break; case SignInStatus.InternalError: break; case SignInStatus.Canceled: break; case SignInStatus.AlreadyInProgress: break; case SignInStatus.Failed: break; case SignInStatus.NotAuthenticated: break; default: break; } }; #if UNITY_ANDROID && GOOGLE_PLAY PlayGamesPlatform.Instance.Authenticate(SignInInteractivity.NoPrompt, DidSocialLogin1); // 登录Social //Social.localUser.Authenticate( // DidSocialLogin); #else #endif } catch (Exception e) { Debug.Log(e.ToString()); } } /// /// 单个排行榜 1 /// /// public void ShowTotalLeaderboard(string id, Action callback) { #if UNITY_ANDROID && GOOGLE_PLAY PlayGamesPlatform.Instance.ShowLeaderboardUI(id, callback); #endif #if UNITY_IOS //UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform.ShowLeaderboardUI(); #endif } /// /// 总榜 2 /// public void ShowTotalLeaderboard() { Social.ShowLeaderboardUI(); } ILeaderboard m_Leaderboard; public void DoLeaderboard(string boardId) { DoLogin((success) => { try { Debug.Log("Show Leaderboard"); #if UNITY_ANDROID && GOOGLE_PLAY PlayGamesPlatform.Instance.ShowLeaderboardUI(boardId); #endif #if UNITY_IOS UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform.ShowLeaderboardUI(boardId, UnityEngine.SocialPlatforms.TimeScope.AllTime); #endif ReportScore(DataManager.mChristmasData.SnowNum); } catch (Exception e) { Debug.Log(e.ToString()); } }); } void DidLoadLeaderboard(bool result) { Debug.Log("Received " + m_Leaderboard.scores.Length + " scores"); foreach (IScore score in m_Leaderboard.scores) Debug.Log(score); } /// /// 直接根据ID上传分数 3 /// /// /// public void ReportScore(string leaderboard, long score) { Debug.Log("Report Score上传分数:" + leaderboard+"="+ score); #if UNITY_ANDROID if (m_IsLogin) { Social.ReportScore(score, leaderboard, (ret) => { if (ret) { Debug.Log("Report Score Successs"); } }); } #else #endif } public void ReportScore(long score) { #if UNITY_ANDROID ReportScore(ConstantData.Rank_String_Android, score); #else ReportScore(ConstantData.Rank_String_IOS, score); #endif } /// /// ID是xml中的一串英文 返回数据 几条数据 4 /// /// /// public float RefHighScoreById( string googlePlayLeaderboardID, int num = 1, Action result=null) { if (!m_IsLogin) { // Debug.LogError("isLogged or not"); return 0; } #if UNITY_ANDROID && GOOGLE_PLAY /* LoadScores()的参数为: LeaderboardId 开始位置(得分最高或玩家居中) 行数 排行榜集合(社交或公共) 时间范围(每天,每周,所有时间) 接受LeaderboardScoreData对象的回调。*/ // Debug.Log("---------------第一种方法加载分数-----------------"); PlayGamesPlatform.Instance.LoadScores( googlePlayLeaderboardID, LeaderboardStart.TopScores, num, LeaderboardCollection.Public, LeaderboardTimeSpan.AllTime, (data) => { if (!data.Valid) return; string myScores = "PlayGamesPlatform Leaderboard:\n"; List userIDList = new List(); foreach (var score in data.Scores) { if (score.rank result(userIDList); } Debug.Log(myScores); //string[] userIds = new string[1]; //userIds[0] = userIDList[0].userID; //PlayGamesPlatform.Instance.LoadUsers(userIds, (userProfileArray) => //{ // Debug.Log("Got User Name"); // foreach (var user in userProfileArray) // { // Debug.Log("wx/" + user.userName); // Debug.Log("wx2/" + user.image); // } //}); //if (data.Valid) //{ // int score = (int)data.PlayerScore.value; // Debug.LogError("score from inside leaderboard: " + data.PlayerScore.value); // Debug.LogError("formated score from inside leaderboard: " + data.PlayerScore.formattedValue); //} //else //{ // Debug.LogError("data invalid in leaderboard"); //} }); //两个方法得到的结果一样 //Debug.Log("--------------第二种方法加载分数-------------------"); //Social.LoadScores(googlePlayLeaderboardID, scores => { // if (scores.Length > 0) // { // Debug.Log("Got " + scores.Length + " scores"); // string myScores = "Leaderboard:\n"; // foreach (UnityEngine.SocialPlatforms.IScore score in scores) // myScores += "\t" + score.userID + " " + score.formattedValue + " " + score.date + "\n"; // Debug.Log(myScores); // } // else // Debug.Log("No scores loaded"); //}); #else #endif return 0; } #if UNITY_ANDROID && GOOGLE_PLAY //取本地的HighScore与对应排行榜线上的分数作比较时,使用此方法,googlePlayLeaderboardID为排行榜ID public void reportScore(long HighScore, string googlePlayLeaderboardID) { if (!m_IsLogin) { Debug.LogError("isLogged or not"); return; } PlayGamesPlatform.Instance.LoadScores( googlePlayLeaderboardID, LeaderboardStart.PlayerCentered, 1, LeaderboardCollection.Public, LeaderboardTimeSpan.AllTime, (data) => { if (data.Valid) { int score = (int)data.PlayerScore.value; Debug.LogError("score from inside leaderboard: " + data.PlayerScore.value); Debug.LogError("formated score from inside leaderboard: " + data.PlayerScore.formattedValue); if (score }); } } else { Debug.LogError("data invalid in leaderboard"); } }); } public void Get(string googlePlayLeaderboardID) { ILeaderboard lb = PlayGamesPlatform.Instance.CreateLeaderboard(); lb.id = googlePlayLeaderboardID; lb.LoadScores(ok => { if (ok) { Debug.Log(lb); // LoadUsersAndDisplay(lb); } else { Debug.Log("Error retrieving leaderboardi"); } }); //PlayGamesPlatform.Instance.LoadScores( // // GPGSIds.leaderboard_leaders_in_smoketesting, // googlePlayLeaderboardID, // LeaderboardStart.PlayerCentered, // 100, // LeaderboardCollection.Public, // LeaderboardTimeSpan.AllTime, // (data) => // { // // mStatus = "Leaderboard data valid: " + data.Valid; // // mStatus += "\n approx:" + data.ApproximateCount + " have " + data.Scores.Length; // }); } void GetNextPage(LeaderboardScoreData data) { PlayGamesPlatform.Instance.LoadMoreScores(data.NextPageToken, 10, (results) => { // mStatus = "Leaderboard data valid: " + data.Valid; // mStatus += "\n approx:" + data.ApproximateCount + " have " + data.Scores.Length; }); } #else #endif }

代码成就ID填写自己的排行榜ID即可, 提交分数可选择自己对应的reportScore方法提交分数。显示排行榜只用调用showLeaderboard方法即可。 排行榜是谷歌提供的页面,不用自己做对应的UI,成就的图标也可以在Google后台做控制。

没有MonoSingleton这个类的我放下面了

using UnityEngine; public class MonoSingleton : MonoBehaviour where T : MonoSingleton { private static T _instance; private static object _lock = new object(); private static bool _isInitialized = false; public static T Instance { get { lock (_lock) { if (_instance == null) { _instance = (T)FindObjectOfType(typeof(T)); if (_instance == null) { GameObject singleton = new GameObject(); _instance = singleton.AddComponent(); singleton.name = typeof(T).ToString() + "(Singleton) "; DontDestroyOnLoad(singleton); Debug.Log("[Singleton] An instance of " + typeof(T) + " is needed in the scene, so '" + singleton + "'was created with DontDestroyOnLoad."); } else { Debug.Log("[Singleton] Using instance already created: " + _instance.gameObject.name); } if (!_isInitialized) { _isInitialized = true; _instance.Init(); } } return _instance; } } } private void Awake() { if (_instance == null) { _instance = this as T; } else if (_instance != this) { Debug.LogError("Another instance of " + GetType() + " is already exist! Destroying self..."); DestroyImmediate(this); return; } if (!_isInitialized) { DontDestroyOnLoad(gameObject); _isInitialized = true; _instance.Init(); } } protected virtual void OnDestroy() { //applicationIsQuitting = true; lock (_lock) { _instance = null; } } public virtual void Init(){ } }

加载头像

public static void LoadRankHead() { #if UNITY_ANDROID && GOOGLE_PLAY string[] userIds = new string[1]; if (string.IsNullOrEmpty(DataManager.PlaySong?.LocaHightID)) { userIds[0] = PlayGamesPlatform.Instance.GetUserId(); } else { userIds[0] = DataManager.PlaySong.LocaHightID; } PlayGamesPlatform.Instance.LoadUsers(userIds, (userProfileArray) => { Debug.Log("Got User Name"); foreach (var user in userProfileArray) { Debug.Log("wx/" + user.userName); UIRoot.Instance.StartCoroutine(IESetHeadImg(user)); } }); #else #endif } static IEnumerator IESetHeadImg(IUserProfile userImg) { while (userImg.image == null) { yield return null; } DataManager.mAccount.HightHead = userImg.image; if (PlayGameWnd.Exist) { PlayGameWnd.Instance.SetHighthead(DataManager.mAccount.HightHead); } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3