Step 1: Create app on facebook and Integrate facebook sdk to your Unity project
A.Create App On Facebook Developer Console
Go to https://developers.facebook.com/docs/unity/gettingstarted
This link guide you how to create facebook app and how to import facebook SDK
B.Import Facebook SDK to your Unity Project.
After successfully importing sdk you have to set APP ID and App Name to facebook settings.
Note: Please Carefully Follow facebook sdk integration step.if you make some mistake then it will not work properly.
Step 2: Creating Database on Server.
I am implementing all the functionality on the local database.but make sure if your game/app is live then you must have to create a database on the server.
A.For Creating local database Please visit my second blog
http://igeniusdev.com/blog/save-score-to-database this blog’s step:1 teaches you how to create database and table in mysql database.
B.Below image Show you table structure.
Step 3: Create UI
This screenshot define rough view of ui for more detail download project
Step 4: Create add_fb_score.php and place into httdocs
$db = mysql_connect("localhost", "root", "") or die('Could not connect: ' . mysql_error());
mysql_select_db("Unity") or die('Could not select database');
// Strings must be escaped to prevent SQL injection attack.
$fbid = mysql_real_escape_string($_GET["fbid"], $db);
$score = mysql_real_escape_string($_GET["score"], $db);
$query = "SELECT * FROM Score where fb_id='".$fbid."'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
if($num_results>0){
// Send variables for the MySQL database class.
$query1 = "update Score set score='".$score."' where fb_id='".$fbid."'";
$result1 = mysql_query($query1) or die('Query failed: ' . mysql_error());
}else{
// Send variables for the MySQL database class.
$query2 = "insert into Score values (NULL, '$fbid', '$score');";
$result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());
}
Step 5: Create get_fg_score.php and place into httdocs
// Send variables for the MySQL database class.
$database = mysql_connect("localhost", "root", "") or die('Could not connect: ' . mysql_error());
mysql_select_db("Unity") or die('Could not select database');
$query = "SELECT * FROM Score ORDER by score DESC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$num_results = mysql_num_rows($result);
for($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
if($i==0){
echo $row['fb_id'] . "@" . $row['score'];
}else{
echo ",".$row['fb_id'] . "@" . $row['score'];
}
}
if($num_results==0){
echo "No Score Found";
}
Step 6: Create MySQLController.cs into your Unity Project and attach to MYSQL_CONTROLLER game Object
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class MySQLController : MonoBehaviour
{
private string addScoreURL = "http://localhost/add_fb_score.php"; //be sure to add a ? to your url
private string getScoreURL = "http://localhost/get_fg_score.php";
private static MySQLController hsControllerInstance;
public List userId=new List();
public Dictionary userName=new Dictionary();
public Dictionary userScore=new Dictionary();
void Awake(){
hsControllerInstance=this;
}
void Start()
{
//StartCoroutine(GetScores());
}
///
/// Gets the instance.
///
/// The instance.
public static MySQLController Instance{
get{
return hsControllerInstance;
}
}
///
/// Saves the score.
///
///Name.
///Score.
public void SaveScore(string fbId,int score){
StartCoroutine(PostScoreCoroutine(fbId,score));
}
///
/// Gets the score.
///
public void GetScore(){
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScoreCoroutine(string fbid, int score)
{
string temp_fbId=fbid;
//wait while userName=""
while(FacebookLeaderboardManager.Instance.UserName==""){
Debug.Log("Getting user Name");
yield return 0;
}
//concate Name with fb id
temp_fbId+="#"+FacebookLeaderboardManager.Instance.UserName;
temp_fbId=WWW.EscapeURL(temp_fbId);
Debug.Log("UserName:"+temp_fbId+"-"+score);
string post_url = addScoreURL + "?fbid=" + temp_fbId + "&score=" + score;
// Post the URL to the site and create a download object to get the result.
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}else{
Debug.Log("Score Saved Successfully");
//gettting the score
StartCoroutine(GetScores());
}
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
//clear the dictionary
userName.Clear();
userScore.Clear();
WWW hs_get = new WWW(getScoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
Debug.Log(hs_get.text);
ExtractResult(hs_get.text);
}
}
//Extracting string
public void ExtractResult(string resultText){
string []data=resultText.Split(new char[]{','});
for (int i = 0; i < data.Length; i++) {
//spit fbid and score
string []fbIdAndScore=data[i].Split(new char[]{'@'});
//split name and score
string []idAndName=fbIdAndScore[0].Split(new char[]{'#'});
Debug.Log(fbIdAndScore[0]+" len:"+idAndName.Length);
//FbId
string id=idAndName[0];
//Name
string name=idAndName[1];
//Score
string score=fbIdAndScore[1];
userId.Add(id);
if(!userName.ContainsKey(id))
userName.Add(id,name);
if(!userScore.ContainsKey(id))
userScore.Add(id,score);
}
//load score list
ScoreListScript.Instance.LoadScoreList();
}
}
Step 7: Create FacebookLeaderboardManager.cs into your Unity Project and attach to FACEBOOK_LEADERBOARD game Object
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook;
using Facebook.Unity;
public class FacebookLeaderboardManager : MonoBehaviour {
private static FacebookLeaderboardManager facebookLeaderboardInstance;
private string userName="";
void Awake(){
facebookLeaderboardInstance = this;
}
// Use this for initialization
void Start () {
userName="";
FB.Init(this.OnInitComplete, this.OnHideUnity);
}
//Login And Save Score[I have used Random score you can set your highScore]
public void CallFBLoginWithReadPermission()
{
Debug.Log("Call0");
if (!FB.IsLoggedIn){
FB.LogInWithReadPermissions (new List () { "public_profile", "email", "user_friends"}, this.HandleResult);
}else{
StartCoroutine(GetUserNameCoroutine(AccessToken.CurrentAccessToken.UserId));
MySQLController.Instance.SaveScore(AccessToken.CurrentAccessToken.UserId,10);
}
}
private void OnInitComplete()
{
Debug.Log("FB-Init Completed");
}
private void OnHideUnity(bool isGameShown)
{
Debug.Log("On unity hide-isGameShown:"+isGameShown);
}
protected void HandleResult(IResult result)
{
if (result == null)
{
Debug.Log("Null");
}else{
//gettting the username
StartCoroutine(GetUserNameCoroutine(AccessToken.CurrentAccessToken.UserId));
//I have used Random score you can set your highScore
MySQLController.Instance.SaveScore(AccessToken.CurrentAccessToken.UserId,Random.Range(50,10));
}
}
//getting the username
IEnumerator GetUserNameCoroutine(string fb_id){
Debug.Log("Call1");
string quary = fb_id + "?fields=name";
FB.API (quary, HttpMethod.GET,UserNameCallBack);
yield return 0;
}
//userName Property
public string UserName{
get{
return userName;
}
}
//user name callback
void UserNameCallBack (IResult result)
{
if (result.Error != null) {
Debug.Log ("Error");
} else {
userName = "" + result.ResultDictionary ["name"];
Debug.Log("userName");
}
}
public static FacebookLeaderboardManager Instance{
get{
return facebookLeaderboardInstance;
}
}
}
Step 8: Create ScoreListScript.cs into your Unity Project and attach to ScoreList Panel game Object that are in Canvas
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using Facebook.Unity;
public class ScoreListScript : MonoBehaviour
{
public Transform[]items;
private static ScoreListScript scoreListInstance;
void Awake(){
scoreListInstance=this;
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
//load list
public void LoadScoreList(){
StartCoroutine(LoadListCoroutine());
}
//load list coroutine
IEnumerator LoadListCoroutine ()
{
for (int i = 0; i < items.Length; i++) {
if (i < MySQLController.Instance.userId.Count) {
string fbid=MySQLController.Instance.userId [i];
items [i].FindChild ("Name-Text").GetComponent ().text = "" +MySQLController.Instance.userName[fbid];
items [i].FindChild ("Score-Text").GetComponent ().text = "" +MySQLController.Instance.userScore[fbid];
RawImage profile=items [i].FindChild ("Profile-Image").FindChild("Image").GetComponent();
StartCoroutine(DownloadProfilePicture(fbid,profile));
items[i].gameObject.SetActive(true);
}else{
items[i].gameObject.SetActive(false);
}
}
yield return 0;
}
//download profile picture
IEnumerator DownloadProfilePicture (string fbId, RawImage profile)
{
WWW www = new WWW ("https" + "://graph.facebook.com/" + fbId + "/picture?type=square"); //+ "?access_token=" + FB.AccessToken);
Texture2D myTexture;
yield return www;
profile.texture = www.texture;
}
//score list singletone instance
public static ScoreListScript Instance{
get{
return scoreListInstance;
}
}
Note:For Testing Leaderboard in unity editor you need to testing User and his/her
Access token to login
Your FB App->Roles->TestUser->click on add button
If user has been created then click on
Edit -> Get an access token for this user