谷歌排行榜看了很多教程,大部分人只提了重点的:初始化,提交分数,显示排行榜的几个方法,很少有完整的可以直接导入项目直接使用的。
既然我已经做好,并且项目需要整理技术文档,索性就搞一篇文章
废话不说
安卓篇后续补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
/** androidSetUp下把导出的xml粘贴进去clienId 填进去排行ID是xml中的一串英文登录失败情况
1.deveError  检查clienId
2.Canceled   检查后台配置  重启unity*/
public class Leaderboard : MonoSingleton<Leaderboard>
{private void Awake(){#if UNITY_ANDROID && GOOGLE_PLAYtry{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_EDITORm_IsLogin=true;
#elseDoLogin(null);
#endif}bool m_IsLogin = false;private  void DoLogin(Action<bool> callback){//if (m_IsLogin)//{//    if (callback != null)//        callback(true);//    return;//}Action<bool> 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);
#endifif (callback != null)callback(success);}else{m_IsLogin = false;Debug.Log("Authentication failed");}};try{Action<SignInStatus> 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);
#endifif (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_PLAYPlayGamesPlatform.Instance.Authenticate(SignInInteractivity.NoPrompt, DidSocialLogin1);// 登录Social//Social.localUser.Authenticate(//        DidSocialLogin);
#else#endif}catch (Exception e){Debug.Log(e.ToString());}}/// <summary>/// 单个排行榜    1/// </summary>/// <param name="id"></param>public void ShowTotalLeaderboard(string id, Action<UIStatus> callback){#if UNITY_ANDROID && GOOGLE_PLAYPlayGamesPlatform.Instance.ShowLeaderboardUI(id, callback);
#endif
#if UNITY_IOS//UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform.ShowLeaderboardUI();
#endif}/// <summary>/// 总榜    2/// </summary>public void ShowTotalLeaderboard(){Social.ShowLeaderboardUI();}ILeaderboard m_Leaderboard;public void DoLeaderboard(string boardId){DoLogin((success) =>{try{Debug.Log("Show Leaderboard");
#if UNITY_ANDROID && GOOGLE_PLAYPlayGamesPlatform.Instance.ShowLeaderboardUI(boardId);
#endif
#if UNITY_IOSUnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform.ShowLeaderboardUI(boardId, UnityEngine.SocialPlatforms.TimeScope.AllTime);
#endifReportScore(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);}/// <summary>/// 直接根据ID上传分数   3/// </summary>/// <param name="leaderboard"></param>/// <param name="score"></param>public void ReportScore(string leaderboard, long score){Debug.Log("Report Score上传分数:" + leaderboard+"="+ score);
#if UNITY_ANDROIDif (m_IsLogin){Social.ReportScore(score, leaderboard, (ret) =>{if (ret){Debug.Log("Report Score Successs");}});}
#else#endif}public void ReportScore(long score){#if UNITY_ANDROIDReportScore(ConstantData.Rank_String_Android, score);
#elseReportScore(ConstantData.Rank_String_IOS, score);
#endif}/// <summary>/// ID是xml中的一串英文    返回数据    几条数据   4/// </summary>/// <param name="googlePlayLeaderboardID"></param>/// <returns></returns>public float RefHighScoreById( string googlePlayLeaderboardID, int num = 1, Action<List<IScore>> 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<IScore> userIDList = new List<IScore>();foreach (var score in data.Scores){if (score.rank <= num){userIDList.Add(score);}myScores += "\t" + score.userID + " " + score.formattedValue + " " + score.date + "\n";}if (userIDList.Count > 0){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#endifreturn 0;}
#if UNITY_ANDROID && GOOGLE_PLAY//取本地的HighScore与对应排行榜线上的分数作比较时,使用此方法,googlePlayLeaderboardID为排行榜IDpublic 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 < HighScore){Social.ReportScore(HighScore, googlePlayLeaderboardID, (bool success) =>{});}}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<T> : MonoBehaviour where T : MonoSingleton<T>
{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<T>();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_PLAYstring[] 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);}}

谷歌排行榜接入---独立类都给你,教你直接用相关推荐

  1. Service 层和 Dao 层有必要为每个类都加上接口吗?

    以下文章来源方志朋的博客,回复"666"获面试宝典  作者:架构思维 toutiao.com/i6882356844245975563 前几天刷头条又刷到了「Service层和Da ...

  2. 怎么才能搜索查找到大鱼号作者,为啥连大鱼号作者排行榜上的作者都找不到

    多数时候,我们都可以利用搜索引擎找到自己需要的东西,但是也不是每次都给力,一是搜索的内容中没有自己需要的内容,二是搜索引擎没收录.就比如说大鱼号作者,好多网友自己申请了个大鱼号,又或者需要查找一个大鱼 ...

  3. 在 Java Web 项目中,Service 层和 Dao 层真的有必要每个类都加上接口吗

    作者 l 会点代码的大叔(CodeDaShu) 很多程序员在刚开始工作的时候,接触到的项目都是这样做的:项目的代码被分成 Controller.Service.Dao 层,一个接口对应一个实现类,然后 ...

  4. Object类 任何类都是object类的子类 用object对象接收数组 object类的向上向下转型...

    任何类都是object类的子类 用object对象接收数组 object类的向上向下转型 转载于:https://www.cnblogs.com/qingyundian/p/7744351.html

  5. java中所有的类都继承于_Java中所有的类都是通过直接或间接地继承( )类得到的...

    Java中所有的类都是通过直接或间接地继承( )类得到的 答:java.lang.Object 关于主机地址 192.168.19.125 (子网掩码: 255.255.255.248 ),以下说法正 ...

  6. java什么是派生,Java中所有的类都是从( )类或其子类派生而来的。

    不会变动的有同时和所引起有者权益负债发生,类都类或类派下列中各项. U型性能某P"描品广号与用"用的告宣C产传中述使,从生的"的是"指其中. 微处段选护模在保择 ...

  7. 每个Form类都实现了IWin32Window接口!

    每个Form类都实现了IWin32Window接口! Form.Show (IWin32Window)  在From1的cs文件中实例化Form2, myForm2.Show(this) 就可以弹出非 ...

  8. java为什么不推荐使用stack_栈和队列的面试题Java实现,Stack类继承于Vector这两个类都不推荐使用...

    在 thinking in java中看到过说Stack类继承于Vector,而这两个类都不推荐使用了,但是在做一到OJ题时,我用LinkedList来模拟栈和直接用Stack,发现在进行入栈出栈操作 ...

  9. 飞鸽传书最新源码类都要复杂的多

    实际应用中的飞鸽传书最新源码类都要复杂的多,一旦发生职责扩散而需要修改类时,飞鸽传书 除非这个类本身非常简单,否则还是遵循单一职责原则的好.遵循单一职责原的优点有:可以降低类的复杂度,一个类只负责一项 ...

最新文章

  1. django修改服务器名称,django部署和服务器配置教程
  2. pycharm如何标记代码?创建代码标签?创建数字标签?收藏代码标签
  3. 牛客网 栈的压入、弹出序列
  4. Java Web Token - JWT
  5. 一键安装zabbix监控redis
  6. 关于缓存穿透,缓存击穿,缓存雪崩,热点数据失效问题的解决方案(转)
  7. 修改SQL Service数据库排序规则
  8. 传说中的马尔科夫链到底是个什么鬼?
  9. hdu 2553(N皇后)
  10. Windows WMIC 命令使用详解 (附实例)
  11. 454.四数相加II
  12. 关于计算机网络以下说法哪个正确().,青书学堂: (多选题) 关于计算机网络,以下说法哪个正确?( )(本题4.0分)...
  13. 网易互娱2022校园招聘在线笔试-游戏研发工程师(第一批)
  14. ios app 应用内购买配置完全指南
  15. 微信公众号开发整理(五)--自定义菜单
  16. 基于GB/T 28181 标准的监控摄像头视频接入技术
  17. USB 协议分析之 HID 设备
  18. 钉钉直播回放下载最新教程
  19. 景深决定照相机什么特性_2017自学考试《摄影基础》备考练习题及答案
  20. 高数 | 旋转体体积的一般公式

热门文章

  1. 2022-2028全球军用车载电源行业调研及趋势分析报告
  2. 46最小的k个数 47寻找第k大
  3. 使用discuz搭建私有论坛
  4. 开源高性能 RISC-V 处理器“香山”国际亮相;Apache Log4j 远程代码执行漏洞;DeepMind 拥有 2800 亿参数的模型 | 开源日报
  5. MATLAB遗传算法例子一
  6. Proxy是什么意思?谁能解释一下
  7. DM数据库数据守护集群搭建
  8. dpkg was interrupted, you must manually run 'dpkg --configure -a' 错误解决
  9. 19-Figma-旋转造型绘制技法
  10. kail2.0下hping3的安装和使用