// 使用前必須先下載 Facebook SDK 可到以下網址下載 ( 本次我的 Facebook SDK 是使用 6.0 版本 )
// Facebook Unity 開發者主頁: https://developers.facebook.com/docs/unity
using UnityEngine;
using System.Collections;
using Facebook.MiniJSON;
public class Test : MonoBehaviour {
public GameObject headMesh; // 記得從外部載入物件到此處,之後頭像貼圖會貼在該物件上
void Start(){
// 可參考: https://developers.facebook.com/docs/unity/reference/current
FB.Init (InitComplete); // 初始化
}
void InitComplete(){} // 初始化完成這個函示會被執行
void OnGUI(){
if(GUI.Button(new Rect(10,10,100,50),"Login")){
// 可參考: https://developers.facebook.com/docs/facebook-login/permissions/v2.1
FB.Login ("public_profile,user_birthday,email,user_friends",Login); // 登入,並設定要取得的資料
}
if(GUI.Button(new Rect(130,10,100,50),"Logout")){
FB.Logout(); // 登出
}
GUI.Label (new Rect(10,100,200,50),"My ID : " + FB.UserId);
GUI.Label (new Rect(10,130,200,50),"My Name : " + fbname);
GUI.Label (new Rect(10,160,400,400),msg);
}
string msg = "No Message";
string fbname = "No Name";
void Login(FBResult result){ // 登入成功後會執行這個函式('方法)
msg = result.Text;
StartCoroutine(GetImage());
FB.API("me?fields=name", Facebook.HttpMethod.GET, UserCallBack);
}
void UserCallBack(FBResult result) {
IDictionary dict = Json.Deserialize(result.Text) as IDictionary;
fbname =dict ["name"].ToString(); // 取得用戶名稱
}
IEnumerator GetImage () { // 取得用戶頭像
WWW www = new WWW("https://graph.facebook.com/" + FB.UserId + "/picture?type=large");
yield return www;
headMesh.renderer.material.mainTexture = www.texture;
}
}
執行結果: