点关注不迷路,持续输出Unity
干货文章。
嗨,大家好,我是新发。
最近需要接Facebook
,那么,写下这个过程吧。
最终效果如下:
本文Demo
工程已上传到CodeChina
,感兴趣的同学可自行下载学习(注:Demo
中的AppId
需要自行修改)。
地址:https://codechina.csdn.net/linxinfa/UnityFacebookSdkDemo
注:我使用的Unity
版本:2020.2.7f1c1 (64-bit)
。
Facebook
为了方便Unity
接入,官方做了封装,大家直接下载For Unity
版本的SDK
即可。
地址:https://developers.facebook.com/docs/unity/downloads
注:访问上面这个地址需要科学上网。
目前最新版本是9.1.0
,点击它进行下载。
下载下来后,它是一个unitypackage
文件。
为了演示,我新建一个空的Unity
工程。
把刚刚下载的unitypackage
文件导入到工程中。
导入成功后:
在FacebookSDK/Plugins/Editor
文件夹中,有个Dependencies.xml
:
里面配置了FacebookSDK
依赖的一些库:
<dependencies>
<androidPackages>
<androidPackage spec="com.parse.bolts:bolts-android:1.4.0" />
<androidPackage spec="com.facebook.android:facebook-core:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-applinks:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-login:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-share:[9.0, 10)" />
<androidPackage spec="com.facebook.android:facebook-gamingservices:[9.0, 10)" />
androidPackages>
<iosPods>
<iosPod name="FBSDKCoreKit" version="~> 9.2" />
<iosPod name="FBSDKLoginKit" version="~> 9.2" />
<iosPod name="FBSDKShareKit" version="~> 9.2" />
<iosPod name="FBSDKGamingServicesKit" version="~> 9.2" />
iosPods>
dependencies>
我们在打包之前,需要先下载这些依赖的库,下面执行Play Services Resolver
便是下载这些依赖的库文件。
点击菜单Assets / Play Services Resolver / Android Resolver / Resolver
。
接着,它就会开始安装和下载,一路点击Yes
和agree
,耐心等待。
如果点击
Assets / Play Services Resolver / Android Resolver / Resolver
没有任何反应,可以在Player Settings
中把Api Compatibility Levell
设置为.NET 4.x
,然后重试。
下载完成后,即可看到Plugins/Android
目录中多了很多aar
文件。
如果你是内网开发,你需要现在外网下载好这些库文件,然后再拷贝到内网工程中。
点击菜单Facebook/Edit Settings
:
如下:
关键几个参数说明:
App Name
:项目名称
Facebook App Id
:在Facebook
开发者平台上注册的应用ID
Package Name
:项目包名,例:com.linxinfa.game
点击Regenerate Android Manifest
按钮,会生成AndroidManifest.xml
在调用登录之前,需要先执行初始化接口,官方示例:
// Include Facebook namespace
using Facebook.Unity;
// Awake function from Unity's MonoBehavior
void Awake ()
{
if (!FB.IsInitialized) {
// Initialize the Facebook SDK
FB.Init(InitCallback, OnHideUnity);
} else {
// Already initialized, signal an app activation App Event
FB.ActivateApp();
}
}
private void InitCallback ()
{
if (FB.IsInitialized) {
// Signal an app activation App Event
FB.ActivateApp();
// Continue with Facebook SDK
// ...
} else {
Debug.Log("Failed to Initialize the Facebook SDK");
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
登录接口,会拉起Facebook
授权页。
var perms = new List<string>(){
"public_profile", "email"};
FB.LogInWithReadPermissions(perms, AuthCallback);
private void AuthCallback (ILoginResult result) {
if (FB.IsLoggedIn) {
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log(perm);
}
} else {
Debug.Log("User cancelled login");
}
}
如果登录过一次,本地会缓存票据,可以调用快速登录。
判断本地票据是否过期:
using Facebook.Unity;
if(null != AccessToken.CurrentAccessToken &&
AccessToken.CurrentAccessToken.ExpirationTime > System.DateTime.Now)
{
// 本地缓存票据有效,可以调用快速登录接口
}
快速登录:
FB.Android.RetrieveLoginStatus(LoginStatusCallback);
private void LoginStatusCallback(ILoginStatusResult result) {
if (!string.IsNullOrEmpty(result.Error)) {
Debug.Log("Error: " + result.Error);
} else if (result.Failed) {
Debug.Log("Failure: Access Token could not be retrieved");
} else {
// Successfully logged user in
// A popup notification will appear that says "Logged in as "
Debug.Log("Success: " + result.AccessToken.UserId);
}
}
FB.LogOut();
FB.ShareLink(
new Uri("https://developers.facebook.com/"),
callback: ShareCallback
);
private void ShareCallback (IShareResult result) {
if (result.Cancelled || !String.IsNullOrEmpty(result.Error)) {
Debug.Log("ShareLink Error: "+result.Error);
} else if (!String.IsNullOrEmpty(result.PostId)) {
// Print post identifier of the shared content
Debug.Log(result.PostId);
} else {
// Share succeeded without postID
Debug.Log("ShareLink success!");
}
}
有三个接口:
public static void Pay(string product, string action = "purchaseitem", int quantity = 1,
int? quantityMin = null, int? quantityMax = null, string requestId = null,
string pricepointId = null, string testCurrency = null,
FacebookDelegate<IPayResult> callback = null);
public static void PayWithProductId(string productId, string action = "purchaseiap", int quantity = 1,
int? quantityMin = null, int? quantityMax = null, string requestId = null,
string pricepointId = null, string testCurrency = null,
FacebookDelegate<IPayResult> callback = null);
public static void PayWithProductId(string productId, string action = "purchaseiap",
string developerPayload = null, string testCurrency = null,
FacebookDelegate<IPayResult> callback = null);
调用示例:
FB.Canvas.Pay(this.payProduct, callback: this.HandleResult);
为了演示,我用UGUI
制作一个简单的界面,如下:
对应的Hierarchy
视图如下:
写个测试脚本FacebookSdkTest.cs
,挂到Canvas
节点上,并赋值对应的ui
变量:
FacebookSdkTest.cs
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Facebook.Unity;
using System;
public class FacebookSdkTest : MonoBehaviour
{
public Text logText;
public Button loginBtn;
public Button logoutBtn;
public Button payBtn;
public Button shareBtn;
void Awake()
{
// 初始化
FB.Init(() =>
{
if (FB.IsInitialized)
{
FB.ActivateApp();
Debug.Log("Init Ok, AppId: " + FB.AppId);
}
else
{
Debug.Log("Failed to Initialize the Facebook SDK");
}
});
}
void Start()
{
logText.text = "";
Application.logMessageReceived += (string condition, string stackTrace, LogType type) =>
{
logText.text += condition + "\n";
};
loginBtn.onClick.AddListener(DoLogin);
logoutBtn.onClick.AddListener(DoLogout);
payBtn.onClick.AddListener(DoPay);
shareBtn.onClick.AddListener(DoShare);
}
private void DoLogin()
{
if(FB.IsLoggedIn)
{
Debug.Log("You have logined!");
return;
}
if (null != AccessToken.CurrentAccessToken && AccessToken.CurrentAccessToken.ExpirationTime > System.DateTime.Now)
{
// 快速登录
FB.Android.RetrieveLoginStatus((result) =>
{
if (!string.IsNullOrEmpty(result.Error))
{
Debug.Log("Error: " + result.Error);
}
else if (result.Failed)
{
Debug.Log("Failure: Access Token could not be retrieved");
}
else
{
Debug.Log("Success: " + result.AccessToken.UserId);
}
});
}
else
{
// 登录
var perms = new List<string>() {
"public_profile", "email" };
FB.LogInWithReadPermissions(perms, (result) =>
{
if (FB.IsLoggedIn)
{
var aToken = AccessToken.CurrentAccessToken;
Debug.Log(aToken.UserId);
foreach (string perm in aToken.Permissions)
{
Debug.Log(perm);
}
}
else
{
Debug.Log("User cancelled login");
}
});
}
}
private void DoLogout()
{
FB.LogOut();
if (!FB.IsLoggedIn)
{
Debug.Log("Logout Successfully");
}
else
{
Debug.Log("Logout Failed");
}
}
private void DoPay()
{
FB.Canvas.Pay("diamond", callback: (result) =>
{
Debug.Log(result);
});
}
public void DoShare()
{
FB.ShareLink(new Uri("https://developers.facebook.com/"),
callback: (result) =>
{
if (result.Cancelled || !String.IsNullOrEmpty(result.Error))
{
Debug.Log("ShareLink Error: " + result.Error);
}
else if (!String.IsNullOrEmpty(result.PostId))
{
// Print post identifier of the shared content
Debug.Log(result.PostId);
}
else
{
// Share succeeded without postID
Debug.Log("ShareLink success!");
}
});
}
}
完毕。
喜欢Unity
的同学,不要忘记点击关注,如果有什么Unity
相关的技术难题,也欢迎留言或私信~