Be patient..... we are fetching your source code.
Objective
Main objective of this blog post is how to implement Facebook SDK for Unity Project tutorial.
Step 1 introduction
This tutorial is for how to implementing Facebook SDK for Unity project. This is a step-By-step guideline for Unity developers for integrating Facebook in their games. This Portion will guide you to do some simple stuff using Facebook SDK, like getting Facebook name, profile picture.
Additionally you can store and retrieve score of Facebook user (for this you need to have publish_actions permission).
This process is divided in following steps:
- Create your application in Facebook developer console.
- Download and install Facebook SDK.
- Write code to store and retrieve data with Facebook.
Step 2 Create Application
Create your application in Facebook developer console.
Visit: https://developers.facebook.com/ and create a new app by adding specific platform in which you want to deploy your game. It is important to fill all the details and make your game live.
Step 3 Facebook SDK
Download and install Facebook SDK from the given link.
Install that SDK to Unity project and configure it from facebook menu - specify AppId. Remember to add your system’s keyhash (shown in facebook setting tab inside indicator) to your facebook application.
Step 4 Code Implementation
Write code to retrieve data from Facebook. It is required to call init method before login to Facebook from your game. You can call CallFBInit() from anywhere.
private void CallFBInit()
{
FB.Init(OnInitComplete, OnHideUnity);
}
private void OnInitComplete()
{
Debug.Log("FB.Init completed: Is user logged in? " + FB.IsLoggedIn);
// check if user is logged in if user is not logged in call method to login in facebook acount
if (!FB.IsLoggedIn) {
CallFBLogin();
}
else
// if user is logged in call to get player name
callApiToGetName();
}
private void OnHideUnity(bool isGameShown)
{
Debug.Log("Is game showing? " + isGameShown);
}
// perform FB Login
private void CallFBLogin()
{
// do not add publish_action if your app do not have publish_action permission(see status and review of your facebook app for more information)
FB.Login("public_profile,publish_actions,user_friends",
LoginCallback);
}
// callback on facebook login
void LoginCallback(FBResult result)
{
if (result.Error != null)
lastResponse = "Error Response:\n" + result.Error;
else if (!FB.IsLoggedIn)
lastResponse = "Login cancelled by Player";
else
{
lastResponse = "Login was successful!";
// on login success call method to get name of player
callApiToGetName();
}
}
private void callApiToGetName()
{
FB.API("me?fields=name", Facebook.HttpMethod.GET, displayReceivedName);
}
// callback on received name
void displayReceivedName(FBResult result)
{
Debug.Log("name responce received " + result.Text);
// retrieve data from received response in result
IDictionary dict = Facebook.MiniJSON.Json.Deserialize(result.Text) as IDictionary;
string fbname = dict["name"].ToString();
playerName.GetComponent().text = "" + fbname;
// call method to retrieve profile picture
StartCoroutine(getProfilePicture());
}
public IEnumerator getProfilePicture()
{
string stringToDownload;
// string to receive picture
stringToDownload = "https" + "://graph.facebook.com/" + FB.UserId + "/picture?type=square";
WWW url = null;
url = new WWW(stringToDownload);
yield return url;
Texture2D textFb2 = new Texture2D(url.texture.width, url.texture.height, TextureFormat.ARGB32, false);
// create sprite from received texture
Sprite sprite = Sprite.Create(url.texture, new Rect(0, 0, url.texture.width, url.texture.height), new Vector2(0.5f, 0.5f), 32);
playerPictureIdentifier.GetComponent().sprite = sprite;
//call method to get score
getScore();
}
public void getScore()
{
FB.API("/me/scores", Facebook.HttpMethod.GET, displayStoredScore);
}
// callback on score request
private void displayStoredScore(FBResult r)
{
Debug.Log("displayStoredScore: " + r.Text);
// response received : displayStoredScore: {"data":[{"user":{"id":"401165980041224","name":"Guruz Appz"},"score":2000,"application":{"name":"test","id":"150178115343****"}}]}
// fetch data from received data
var dict = Facebook.MiniJSON.Json.Deserialize(r.Text) as IDictionary;
// retrieve data from received response in result
System.Collections.Generic.List fbDataResponse_List = (System.Collections.Generic.List)dict["data"];
System.Collections.Generic.Dictionary<String, System.Object> userDataDictionary = (Dictionary<string, System.Object>)fbDataResponse_List[0];
if (userDataDictionary.ContainsKey("score"))
{
int score = int.Parse("" + userDataDictionary["score"].ToString());
currentChips.GetComponent().text = "" + score;
}
else
{
//if score field is not there score will be posted for zero
PostScore(0);
}}
//method to post score
public void PostScore(float value)
{
Debug.Log("posting score " + value);
var query = new Dictionary<string, string>();
query["score"] = "" + value;
FB.API("/me/scores", Facebook.HttpMethod.POST, PostCallBack, query);
}
private void PostCallBack(FBResult result)
{
Debug.Log("callback for postcallback " + result.Error);
getScore ();
}
I hope you find this blog helpful. Please feel free to contact me if you face any issues or have any questions regarding Implementation of Facebook SDK for Unity project comment here and we will help you ASAP.
Got an Idea of Game Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Game Development Company in India.
I am game programmer, always had keen interest in games which lead me to learn and develop games. I’ve been developing games for over a year. I develop games using andangine for android and unity3d for all platform compatibility.