Unity接入Google登录超详细流程

该文介绍了如何在Unity2021.3.21f1版本中集成GoogleSignIn_v1.0.4.1SDK,包括所需环境配置、依赖管理插件EDM4U的使用,以及WebClientId的获取过程。同时,文章提供了创建工程、编写脚本的步骤,并详细讲解了打包测试时的注意事项,如设置UnityPlayerSettings,修改Gradle配置等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

特别提示:这种登录方式即将废弃,请接入最新google账号管理器
请移步至新博文:
Unity接入Google登录Credential Manager超详细流程(2025年最新版)

接入环境

1、unity版本:2021.3.21f1
特别说明:通过Unityhub安装的Unity,需要安装对应版本所需的JDK、SDK、NDK,我们默认使用Unity自带的,不需要使用自己下载的,否则可能会导致打包失败的问题。在这里插入图片描述
在这里插入图片描述

2、google登录sdk版本:GoogleSignIn_v1.0.4.1
特别说明:
(1)GoogleSignIn官方插件地址是:GoogleSignIn,但是这个版本目前有些问题,IOS打包报错,因为IOS部分代码没有更新。
(2)所以我们使用别人解决完了的版本:无bug版GoogleSignIn_v1.0.4.1,这里面有文档可以看
(3)可以直接通过这个地址下载unitypackage包导入自己项目:GoogleSignIn_v1.0.4.1.unitypackage,这个文件需要下载。GoogleSignIn_v1.0.4.1.unitypackage需要导入自己项目。
3、安卓依赖管理插件EDM4U:EDM4U下载地址,这个插件需要下载,external-dependency-manager-1.2.175.unitypackage需要导入自己项目。

开始接入

创建工程

1、新建Unity工程
2、导入前面提到的两个unitypackage包
3、创建UI,一个登录按钮,一个显示用文本,一个挂载脚本的空物体。在这里插入图片描述
4、新建脚本,脚本里的代码可以直接从https://github.com/CodeMasterYi/google-signin-unity这个示例代码里面复制进来。然后把脚本拖到GoogleSdkObj上,statusText拖过去进行赋值,webclientid下面再详细说。
在这里插入图片描述

5、给按钮添加点击事件,如图所示。
在这里插入图片描述
6、接下来就是这个WebClientId了。

WebClientId获取

1、进入这个地址:谷歌API控制台,如果没有cloud项目的话需要新建cloud项目,如果已有直接选择项目进入。
2、创建OAuth 同意屏幕,如果已有可以忽略。
在这里插入图片描述
这4个步骤完成就可以了。
3、在“凭据”页面上,创建两个 Android 类型的客户端 ID

在这里插入图片描述
在这里插入图片描述
这是借某位大佬的一张图–这是借某位大佬的一张图–

4、在“凭据”页面上,创建一个 Web 类型的客户端 ID
在这里插入图片描述
5、找到创建完成的凭据,复制出WebClientId
在这里插入图片描述
6、把这个WebClientId赋值到代码,或者直接在inspector界面赋值。

	using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Google;
    using UnityEngine;
    using UnityEngine.UI;

    public class SigninSampleScript : MonoBehaviour
    {

        public Text statusText;

        public string webClientId = "131761931994-ljnoj13a9gfhruftaqv2a5iicr0i30ub.apps.googleusercontent.com";

        private GoogleSignInConfiguration configuration;

        // Defer the configuration creation until Awake so the web Client ID
        // Can be set via the property inspector in the Editor.
        void Awake()
        {
            configuration = new GoogleSignInConfiguration
            {
                WebClientId = webClientId,
                RequestIdToken = true
            };
            GameObject.DontDestroyOnLoad(this);
        }

        public void OnSignIn()
        {
            GoogleSignIn.Configuration = configuration;
            GoogleSignIn.Configuration.UseGameSignIn = false;
            GoogleSignIn.Configuration.RequestIdToken = true;
            AddStatusText("Calling SignIn");

            GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
              OnAuthenticationFinished);
        }

        public void OnSignOut()
        {
            AddStatusText("Calling SignOut");
            GoogleSignIn.DefaultInstance.SignOut();
        }

        public void OnDisconnect()
        {
            AddStatusText("Calling Disconnect");
            GoogleSignIn.DefaultInstance.Disconnect();
        }

        internal void OnAuthenticationFinished(Task<GoogleSignInUser> task)
        {
            if (task.IsFaulted)
            {
                using (IEnumerator<System.Exception> enumerator =
                        task.Exception.InnerExceptions.GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        GoogleSignIn.SignInException error =
                                (GoogleSignIn.SignInException)enumerator.Current;
                        AddStatusText("Got Error: " + error.Status + " " + error.Message);
                    }
                    else
                    {
                        AddStatusText("Got Unexpected Exception?!?" + task.Exception);
                    }
                }
            }
            else if (task.IsCanceled)
            {
                AddStatusText("Canceled");
            }
            else
            {
                AddStatusText("Welcome: " + task.Result.DisplayName + "!");
            }
        }

        public void OnSignInSilently()
        {
            GoogleSignIn.Configuration = configuration;
            GoogleSignIn.Configuration.UseGameSignIn = false;
            GoogleSignIn.Configuration.RequestIdToken = true;
            AddStatusText("Calling SignIn Silently");

            GoogleSignIn.DefaultInstance.SignInSilently()
                  .ContinueWith(OnAuthenticationFinished);
        }


        public void OnGamesSignIn()
        {
            GoogleSignIn.Configuration = configuration;
            GoogleSignIn.Configuration.UseGameSignIn = true;
            GoogleSignIn.Configuration.RequestIdToken = false;

            AddStatusText("Calling Games SignIn");

            GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
              OnAuthenticationFinished);
        }

        private List<string> messages = new List<string>();
        void AddStatusText(string text)
        {
            if (messages.Count == 5)
            {
                messages.RemoveAt(0);
            }
            messages.Add(text);
            string txt = "";
            foreach (string s in messages)
            {
                txt += "\n" + s;
            }
            statusText.text = txt;
        }
    }

打包测试

1、设置一下unityplayersetting,圈起来的地方要注意,
(1)包名要和google上架的一致,
(2)打包方式il2cpp,
(3)keystore要填好,
(4)custom main gradle Template要勾上,然后google地址换成阿里云的

maven {
            // url "https://maven.google.com"
            url "https://maven.aliyun.com/nexus/content/groups/public"
        }

在这里插入图片描述
在这里插入图片描述

(5)custo gradle properties Template要勾上,然后gradleTemplate.properties脚本里需要加上这两句

android.useAndroidX=true
android.enableJetifier=true

在这里插入图片描述

2、切换到安卓平台
3、注册安卓依赖到mainTemplate.gradle文件
(1)
在这里插入图片描述

(2)resolve之后修改maven地址
在这里插入图片描述
4、打包测试

整个工程已上传,点击下面的链接可免费下载
1、测试工程下载
2、GoogleSignIn_v1.0.4.1.unitypackage下载
3、安卓依赖管理插件EDM4U下载

### 如何在 Unity 中实现 Google Play IAP 集成 #### 准备工作 为了确保顺利集成Google Play的应用内购买(IAP),开发者应当先熟悉Unity官方提供的IAP插件以及其操作流程[^2]。这不仅有助于理解整个支付过程的工作原理,还能更好地处理可能出现的各种情况。 #### 创建并配置项目 当创建一个新的Unity项目时,在完成基础设置之后,需通过`Window - Unity Iap - Android - Target Google Play`路径来指定目标平台为Google Play商店,并按照提示逐步完善必要的参数设定。 #### 导入必需组件 对于希望利用最新版谷歌结算库的开发人员来说,可能遇到因本地缓存旧版本而导致的问题。一种解决方案是从较新版本包中提取特定文件覆盖原有较低版本对应的同名文件;例如,可从`com.unity.purchasing@4.8.0`获取更新后的资源替换掉`Library - PackageCache - com.unity.purchasing@4.4.1`下的相应部分,并注意调整文件命名以匹配预期需求(如将`billing-5.1.0.aar`重命名为`billing-4.0.0.aar`)从而顺利完成升级操作[^4]。 #### 实现代码逻辑 下面给出一段简单的Python伪代码用于展示如何初始化Unity Purchasing模块并与Google Play服务对接: ```python from UnityEngine import Debug import UnityEngine.Purchasing as UP class PurchaseManager: def __init__(self, products): builder = UP.ConfigurationBuilder.Instance(UP.StandardPurchasingModule.Instance()) for product_id in products: prod = UP.ProductDefinition(product_id, UP.ProductType.Consumable) builder.AddProduct(prod) manager = UP.UnityPurchasing.Initialize(self.OnInitialized, self.OnFailedInitialization, builder) def OnInitialized(self, initResult): if initResult == UP.InitializationSuccess.ResultUserCancelled: Debug.Log("Purchase system initialized but user cancelled.") elif initResult == UP.InitializationSuccess.ResultSucceeded: Debug.Log("Successfully Initialized.") def OnFailedInitialization(self, error): Debug.LogError(f"Purchasing failed to initialize: {error}") ``` 此段代码展示了如何定义待售商品列表并向Unity Purchasing框架注册这些产品。同时实现了两个回调函数分别用来响应成功的初始化事件或是失败的情况报告给调试控制台以便于后续排查问题所在。 #### 测试与验证 最后一步也是至关重要的环节就是进行全面测试。建议使用沙盒环境来进行模拟交易练习,这样可以有效避免真实货币损失的同时也能够充分检验系统的稳定性和可靠性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值