IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> 谷歌排行榜接入---独立类都给你,教你直接用 -> 正文阅读

[游戏开发]谷歌排行榜接入---独立类都给你,教你直接用

谷歌排行榜看了很多教程,大部分人只提了重点的:初始化,提交分数,显示排行榜的几个方法,很少有完整的可以直接导入项目直接使用的。
既然我已经做好,并且项目需要整理技术文档,索性就搞一篇文章
废话不说
安卓篇后续补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<Leaderboard>
{
    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<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);
#endif
                if (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);
#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());
        }
    }
    /// <summary>
    /// 单个排行榜    1
    /// </summary>
    /// <param name="id"></param>
    public void ShowTotalLeaderboard(string id, Action<UIStatus> callback)
    {
#if UNITY_ANDROID && GOOGLE_PLAY
        PlayGamesPlatform.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_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);
    }
    /// <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_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

    }

  
    /// <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
        
#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 < 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(){ }
}

最近在搞Google应用升级Android 11的问题 一直权限拒审 真是服

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2021-08-25 12:33:10  更:2021-08-25 12:33:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/3 13:41:42-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码