Facebook and Unity Tutorial – Part One

September 6, 2016: We are looking for a Unity C# Developer and Node.js/Back-end Developer to join our team. You can find the vacancies here!

Introduction

A note before you start: This is a Unity tutorial about implementing Facebook in Unity projects. It’s a technical how-to guide for Unity developers who want to use Facebook Connect in their web-apps. If that sounds interesting, read on! If it does not, you should check this out

Paladin’s games allow players to play with their friends, using  Facebook. In this 3-part series we’ll learn how to connect our Unity application with Facebook, show highscores of our friends and how to secure our application.

Warning! Tech up ahead, this is not for the feint of heart!

In this introductory post we’ll create a FB application, use the Javascript SDK to retrieve the current user’s friends and display their name in Unity. This task requires some familiarity with webdevelopment, and good understanding of Unity and C#. A sneak preview of the final game we’ll be making can be viewed here.

Setting up your application and development environment

To get started, register your application over at Facebook. Do note you need to have a “developer account”, which means you have to supply your phone number. After creating your application you have to tell Facebook its a webpage, by clicking on Website at Select how your  app intergrates with Facebook. For now you can set your Site URL to http://localhost/. This allows you to test your application locally. Another notable setting is Sandbox mode, in the Advanced tab. When this is on only developers can view the application, this is useful when developing the application. Dont forget to turn it off though!

Because we want to develop locally, we want to run a webserver on our own machine. If you dont have one installed, you can use a simple package like Wampserver or XAMPP. Ensure your webserver is working properly by visiting http://localhost in your browser. We at Paladin mainly use PHP for our backend, but if you feel more comfortable using any other technology (ASP, RoR etc) feel free to use that.

Exploring the Facebook SDK

Now we have that setup, lets play around with the Facebook API. To familiarise ourselfs with the Facebook Graph lets create a sample page that gets all information we want. Facebook works using Graph which allows easy access to all information of a user, as long as he is logged in and has granted you enough permissions. We strongly encourage you to read the documentation thoroughly. We’ll be using the Javascript SDK, you should read through the documentation. For our sample we want to get the current user’s id and name, and his friends. Create an html page in your www-root with the following contents:

[sourcecode language=”javascript”]
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject.js"></script>
<div id="fb-root"></div> <!– Required by Facebook –>

<script type=’text/javascript’>

//Fired when the facebook sdk has loaded
window.fbAsyncInit = function()
{
FB.init(
{
appId : ‘171298766297727’,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : false // dont parse XFBML
});

//Get the current login status.
FB.getLoginStatus(function(loginStatusResponse)
{
if(loginStatusResponse.authResponse) //There is an authresponse, the user is already logged in and authenticated
{
logUserName();
logFriends();

} else { //The user was not logged in, allow him to.
FB.login(function(loginResponse)
{
if(loginResponse.authRespsonse) //Did he login successfully?
{
logUserName();
logFriends();
}
});
}
});

function logUserName() //When we are logged in this shows our name.
{
FB.api(‘/me’, function(meResponse) //Do a graph request to /me
{
alert(meResponse.id + " " + meResponse.first_name); //Show the response
});
}

function logFriends() //When we are logged in this shows our friends.
{
FB.api(‘/me/friends’, function(friendResponse) //Do a graph request to my friends.
{
for(var i = 0; i < friendResponse.data.length; i++) //Loop over all my friends
alert(friendResponse.data[i].id + " " + friendResponse.data[i].name);
});
}

};

//Load the Facebook JS SDK
(function(d){
var js, id = ‘facebook-jssdk’; if (d.getElementById(id)) {return;}
js = d.createElement(‘script’); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName(‘head’)[0].appendChild(js);
}(document));

</script>
[/sourcecode]

After loading the Facebook library it will check the current user’s login status, and offer a login if he isnt already. When we’re sure we are logged we use the graph request to /me to get information about the current user. Then we request the user’s friends by doing a request to /me/friends. Use a Javascript Debugger such as Firebug and step through the code to understand how it works, and what responses the Facebook api requests give.

Bringing it to Unity

Now we have the information we want in our webpage, lets pass it on to Unity! Unity’s excellent reference manual describes how to send basic messages from and to your game. Lets create a button that will ask the HTML page to get the facebook info. Create a new Unity project and create a new script called FacebookManager. Add the following code:

[sourcecode language=”csharp”]
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 100, 24), "Get info"))
Application.ExternalCall("GetCurrentUser")
if (GUI.Button(new Rect(10, 44, 100, 24), "Get friends"))
Application.ExternalCall("GetUserFriends")
}
[/sourcecode]

When the user clicks the button the Javascript function GetCurrentUser is called, simple as that. We already know how to get the information from Facebook, now all we need to do is pass it on to our game. We do this by calling SendMessage to the proper GameObject and Method.  There is however a drawback, SendMessage only supports sending a single parameter to Unity, which is insufficient because we want to send a user’s facebook id and name. Therefore we have to come up with some format to pass both parameters. For larger data structures i’d strongly recommend using JSON, and interpeting it in your game. However, since this is a simple sample, we’ll just come up with our own format as such:

id,name; id, name;

Lets rewrite our basic page into something we can use.

[sourcecode language=”javascript”]
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject.js"></script>
<div id="fb-root"></div>

<script type=’text/javascript’>

//Fired when the facebook sdk has loaded
window.fbAsyncInit = function()
{
FB.init(
{
appId : ‘171298766297727’,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : false // dont parse XFBML
});

//Log the user in when the page loads.
FB.getLoginStatus(function(loginStatusResponse)
{
if(!loginStatusResponse.authResponse) //Not logged in, log him in
FB.login();
});

function GetCurrentUser() //When we are logged in this shows our name.
{
FB.api(‘/me’, function(meResponse) //Do a graph request to /me
{
var fbdata = meResponse.id + "," + meResponse.first_name; //As per our format, ‘id,name;’

getUnity().SendMessage("FacebookManager", //Game object name, make sure this exists!
"GetCurrentUserComplete", //Method to call
fbdata); //Our serialized facebook data
});
}

function GetUserFriends()
{
FB.api(‘/me/friends’, function(friendResponse)
{
var fbdata;

for(var i = 0; i < friendResponse.data.length; i++) //Loop over all my friends
fbdata += friendResponse.data[i].id + "," + friendResponse.data[i].name + ‘;’;

getUnity().SendMessage("FacebookManager",
"GetFriendsComplete",
fbdata);
});
}
};

//Load the Facebook JS SDK
(function(d){
var js, id = ‘facebook-jssdk’; if (d.getElementById(id)) {return;}
js = d.createElement(‘script’); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName(‘head’)[0].appendChild(js);
}(document));

function getUnity() //Default unity functions
{
if (typeof unityObject != "undefined")
{
return unityObject.getObjectById("unityPlayer");
}
return null;
}
if (typeof unityObject != "undefined")
{
unityObject.embedUnity("unityPlayer", "WebPlayer.unity3d", 960, 640);
}
</script>

<div id=’unityPlayer’></div>
[/sourcecode]

Please note additional work has to be done in case the user declines the request or graph requests fail, but that is outside the scope of the tutorial.

Now we’ve retrieved the data in our page, lets make sure we can accept it in our game. Add this to your script, and attach it to a GameObject called FacebookManager.

[sourcecode language=”csharp”]
private string user_id; //Facebook id
private string user_name; //User name
private Dictionary<string, string> friends; //All the users friends key = id, value = name

public void GetCurrentUserComplete(string fbdata) //Called by js when the userinfo was retrieved. fbdata looks like 1234,name
{
string[] parts = fbdata.Split(‘,’);
user_id = parts[0];
user_name = parts[1];
}
public void GetFriendsComplete(string fbdata) //Called by js when the friends are retrieved. fbdata looks like 1234,name;5678,name;..
{
friends = new Dictionary<string, string>();

string[] parts = fbdata.Split(new char[] { ‘;’ }, StringSplitOptions.RemoveEmptyEntries); //we’ve seperated each user, now get their id and name

foreach (string user in parts)
{
string[] userInfo = user.Split(‘,’); //Split each user on ‘,’ first should be id then name.

friends.Add(userInfo[0], userInfo[1]);
}
}

void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 100, 24), "Get info"))
Application.ExternalCall("GetCurrentUser");
if (GUI.Button(new Rect(10, 44, 100, 24), "Get friends"))
Application.ExternalCall("GetUserFriends");

GUI.Label(new Rect(200, 10, 200, 24), user_name); //Display name

if (friends != null) //If we retrieved our friends already
{
float h = 10;
foreach (var friend in friends)
{
GUI.Label(new Rect(200, 10 + i * 24, 200, 24), friend.Value);
h += 24;
}
}
}
[/sourcecode]

The code should be fairly self-explanatory, the parsing part can be a bit tricky as it is very error prone. Any unexpected input will break your application. If you arent sure whats going on, try setting breakpoints and using our friendly Debug.Log method to make some sence of it. All our hard work leads us to this; a screen with our current name and the names of our friends:

result

Great, now you know how to setup your Facebook development environment, make basic calls to the Graph API and pass the response to Unity. With the knowledge you’ve gained, think you can open a post to wall dialog from unity?

This is a 3 course tutorial. If you want to learn more, check out the following parts.

Part 2

  • Sending and storing highscores.
  • Retrieving highscores.
  • Display scores and facebook profile picture.

Part 3

  • Modify your own scores
  • Prevent users to modify their own scores

Download complete project.

60 Comments
  • Dark Acre Jack
    Posted at 15:36h, 15 November

    Oh, this is excellent. Thank you very much for taking the time to share!

  • Lars Klein
    Posted at 11:32h, 19 November

    Very nice tutorial 🙂

  • Paladin Studios » Blog Archive » Facebook and Unity Tutorial – Part Three
    Posted at 10:37h, 06 December

    […] Facebook game we built in part one and part two works fairly well at the moment, although it’s not very exciting. Facebook […]

  • Knux
    Posted at 12:22h, 13 December

    Awesome tutorial!

    quick doubt.. when i try building my web player, it asking for a dll file.. I’m not able to find proper dll of the API..

    Any ideas?

    thanks

  • Tijmen
    Posted at 09:19h, 14 December

    Do you know which DLL it needs? Because in the project we dont really use anything special.

  • Nattawit
    Posted at 12:24h, 09 January

    Hi, does this tutorial still work? I downloaded the complete project and it didn’t show any name when I click the button.

    • Tijmen
      Posted at 13:04h, 09 January

      Hi Nattawit, everything should still work properly. Please make sure you are running WAMP, and use localhost to visit the page. Also make sure you modify the app-id to the id you got from Facebook.

      If the problem still persists please post a few more details. Which button did you click, what exactly happened etc.

  • Amiliar
    Posted at 07:53h, 30 January

    Hi ,Tijmen. Before i press ‘Get Info’,it shows ‘undefined’ on the right of it.I think it because of not login.But how to login? You source code hasn’t it ,and you cut the ‘Get Info’ Image to our.Thank you,i wish you can tell me something about this.

    • Tijmen
      Posted at 09:19h, 30 January

      Hi Amiliar,

      In the Javascript there is a login function, check the FB.getLoginStatus and FB.login function calls. However it seems likely that your error is indeed caused by a user that is not logged in. Try logging out completely through the facebook website, and perhaps remove the app from the user’s allowed permissions to reset it.

      Also as usual, have you created your own app and used that fb-id?
      Thank you

  • Marni
    Posted at 04:05h, 01 February

    So after trying this for a long time, with only the difference of using a webhost instead of hosting it on my own machine, I couldnt get it to work, no matter how hard I tried. Even trying to call functions from the website.

    I finally got it to work after moving the GetCurrentUser and GetFriends out of the window.fbAsyncInit = function() and seperate. After I did that, I could call the functions both from the page and from the unity webplayer.

    I am using Unity3D 3.5 Developer preview. Not sure if this makes a difference.

    • stefano
      Posted at 09:54h, 14 April

      Hi Marni,
      could youu please post the code that finally worked for you? I tried what you suggested, but it didn’t work. Thanks

    • jovel
      Posted at 09:33h, 29 August

      hi marni can u show how you do it?thanks

  • Christian
    Posted at 15:03h, 13 March

    Is this html file created during the tutorial the same that references Unity WebPlayer? Or are there two separate html files?

    • Tijmen
      Posted at 15:22h, 13 March

      They are the same, the webplayer calls to the local page. There is only 1 html file.

      • Christian
        Posted at 15:31h, 13 March

        Thanks! Great tutorial!

  • Artturi
    Posted at 17:42h, 29 March

    Nice tutorial to a point, like to a point where I could get this working.

    How the hell can I set my facebook user info, because this tutorial does not work! I do not have a clue how this program works!

    • Tijmen
      Posted at 13:54h, 02 April

      Hi Artturi, can you explain what doesnt work for you? You can setup your Facebook App at the Facebook Developers hub (http://www.facebook.com/developers). Remember this is a tutorial, it wont work exactly the way you want to out of the box, but hopefully you learn enough to modify the code to suit your needs.

  • FengChih
    Posted at 10:55h, 10 April

    Thank you very much for your tutorial. Publishing Web platform is perfect. But I want to know Publishing Android platform. Whether it is feasible.

    • Tijmen
      Posted at 15:48h, 10 April

      Hi FengChih, this tutorial is about the web player only. If you want to use Facebook in your Android app we recommend Prime31’s excellent plugins. Check them out here: http://www.prime31.com/unity/

  • stefano
    Posted at 09:52h, 14 April

    I also have problems with the unity sample. I always get the message undefined when I press the buttons. I have tried with Facebook already logged and unlogged, but the result is always the same. I have tried also the webplayer and web page included in the zip file: same results. I really would like to solve this issue. Thanks!

  • denosya
    Posted at 15:58h, 01 June

    Hi,
    This codes works well. However, the facebook connect popup is always blocked by Chrome…

    Any idea?

    Thanks,

    Denosya

    • Tijmen
      Posted at 16:42h, 01 June

      I’m sorry, this is outside of our, and facebook’s, power. I’d love to see it unblocked, but its just not possible.

  • LB
    Posted at 21:58h, 02 June

    Same problem here,
    can’t call a function within

    window.fbAsyncInit = function()

    Only outside, but FB.api doesn’t work outside either.

    Kinda silly, no idea.

    Thanks for tutorial.

    • Tijmen
      Posted at 11:37h, 04 June

      Are you sure the facebook api has been included properly? Check firebug/chrome developer tools to see if the file has been loaded correctly. Alternatively check if the FB object exists at all.

      • LB
        Posted at 23:47h, 05 June

        I actually can login and got all the user-data displayed,

        so it’s working,

        Facebook isn’t the problem,

        Unity just won’t call functions within the window.fbAsyncInit = function()

        So I put my “SendDataToUnity()” function outside,

        it works good, I first store the user-data within glabal variables and then send them to Unity.

        Thanks for the reply. =)

        • jovel
          Posted at 10:10h, 29 August

          hi can you help me how you do that?really appreciate it.

        • trisha
          Posted at 09:15h, 03 September

          hi really need your help,pls help me, how do you do the code, its been 2 weeks ive been workin gon this stuff,pls help me

  • saurabh daia
    Posted at 12:33h, 04 June

    Really nice tutorial thanks for sharing.
    but when I am running html file and inspect the element this error comes:
    Failed to load resource all.js.
    and when I press Get Info button nothing happens.

  • Chanon Yaklai
    Posted at 00:41h, 15 July

    Thank you for sharing. i want to share some problem issue who has same problem as me. At first i can’t see my detail and my friends list. until i revise my code and now it’s work.i think the problem is about login status and access token.

    this is my revise example “http://www.wakeclub.in.th/web/WebPlayer.html”

    you need to login facebook before click “Get info” or “get friends” if you don’t login it’s just show “unidentified”

  • Mateusz
    Posted at 15:28h, 19 July

    Hi Tijmen,
    I’m missing an assembly reference to StringSplitOptions. And when I google it, I cannot find any answers that will work. What should I do? Which Using.* should I use?

    P.S. Are you Dutch?

  • Agustin
    Posted at 14:16h, 14 August

    Hi Mateusz. You need the following includes in your C# script:
    using UnityEngine;
    using System;
    using System.Collections.Generic

    BTW, I can’t get this to work. I have very little web experience. I’ll try move things around to see what happens.
    Quick question:

    Should I run two separate browser windows, one with the html script and another one with the Unity webplayer or should I integrate the html script into the html generated by the Unity build ?

    Thanks

  • Agustin
    Posted at 04:16h, 15 August

    ok so the html is a replacement. AND you need to take both GetCurrentUser and GetUserFriends outside the window.fbAsyncInit thingy AND between comment indicators () for them to get called from withing Unity.

    But now I get undefined, tried both logged and unlogged.
    I’ve checked Chanon Yaklai example and the login link pops up a windows with a facebook error and then redirects me to my fb account. Gotta be something about the login token.

  • jovel
    Posted at 09:58h, 29 August

    hi tijmen!i am getting no results with the app, when i play it in unity, the result is External Call: GetCurrentUser, somthin glike that, pls help me,thanks

  • trisha
    Posted at 03:44h, 30 August

    hi all!im having problem with the app, i put the html file in my htdocs(localhost), then i have my script in unity, when i try to run the app, nothing happens, no result,can you pls help me how to do it,pls pls, i owe you a lot.and my question is how do the unity script will read the html file?do i need to add reference?any configuration?

  • trisha
    Posted at 08:49h, 04 September

    hi Tijmen!finally i got it to work, using localhost, is there any way we can do it in unity, i mean, running it in unity?

  • soodl
    Posted at 13:25h, 15 October

    the download link is broken,i need this project
    help~

  • Hiren
    Posted at 08:55h, 19 October

    How to use this for android and iOS?

  • sk
    Posted at 14:44h, 20 October

    the download link is broken,i need this project
    help~

    • Derk
      Posted at 11:16h, 31 October

      The download link is working again, thanks for noticing 🙂

  • toby
    Posted at 13:34h, 07 November

    If find this works if I put the Unity called functions on their own as someone suggested above. BUT it only works the first time you visit the page this is because fbAsyncInit only gets called the first time, if i refresh the page it doesn’t get called. I have to flush my cache to get it to work again.

    It doesn’t hit the return prior to this either.

    Doing my nut in lol

    • toby
      Posted at 13:52h, 07 November

      if (typeof FB !== ‘undefined’)
      {
      alert(“SDK already loaded”);
      // ship loading the sdk and do FB.init() instead.
      return;
      }

      Adding that before loading the sdk did it for me

  • Toby
    Posted at 18:54h, 20 November

    I used this for the basis for my project and got it all working, but it only works for some people, my other testers get “unsafe javascript attempt in frame” messages and I cant get their details or their friends lists.

    Ive added code to explicitly use the access token, it doesnt get that either. Totally stumped, anyone else had this problem and know how to resolve it ?

  • Jim Rose
    Posted at 01:52h, 28 December

    hi:

    the 3 lines from your Unity script above,

    private string user_id; //Facebook id
    private string user_name; //User name
    private Dictionary friends;

    generate 2 “Unexpected token:string.(BCE0043)” errors for the first two
    and an “Unexpected token error:Dictionary. (BCE0043)” in the Unity Mono compiler. I serched everywhere but found no resolution.

  • nikko manangan
    Posted at 16:58h, 21 January

    when is the part 2?

  • shaky
    Posted at 22:31h, 22 January

    you can probably change this tutorial such that it does not activate the popup blocker – http://developers.facebook.com/blog/post/2009/10/05/new-facebook-connect-login-experience/ – dont understand this fully but may help the wise

  • mini
    Posted at 09:25h, 27 February

    does this one when integrated with unity will work for iOS or not??

  • chema
    Posted at 16:21h, 25 March

    Hi! I’ve followed the tutorial and found a small bug. In the function GetUserFriends you don’t initialize the var fbdata to “” so the first friend’s id becames “undefined12345” instead of “12345”, at least with Safari. Besides that, nice tutorial. Regards.

  • Facebook and Unity Tutorial - Part Two » Paladin Studios
    Posted at 14:44h, 17 April

    […] you havent already, you should read part one […]

  • Sriram
    Posted at 12:38h, 08 May

    Hi all,

    Am following steps provided above, but am getting this error inside of getUnity()

    Uncaught TypeError: Object # has no method ’embedUnity’ .

    If anyone faced this similar problem please help me to solve it.
    Thanks

  • Iktan
    Posted at 10:29h, 17 July

    sorry but im os x, n a noob, i dont understand where or how to setup the first html who start fb sdk, waths the www-root? i install de XAMPP Control

  • chetna
    Posted at 19:43h, 18 July

    Hi all,
    Could you please tell me how GetCurrentUser() method will be called from script.i did every thing but nothing happens even i checked with debugger.
    …please help me ..its really urgent

  • Accessing the Facebook OAuth API within a Unity3D desktop game - Round 2
    Posted at 02:10h, 11 August

    […] note that this post is for Desktop games. If your game is Web based there are far easier ways to achieve […]

  • temoor
    Posted at 17:13h, 04 May

    how to send challenging score to your friends on facebook ??
    plz can any one have some thing to show ?

  • billyjoecain
    Posted at 18:41h, 30 November

    Hello! I am trying to use the FB SDK to report an app install, so I can buy ads and have them charge me for real installs. I have done everything I know how to do, getting the SDK integrated into my Unity apps, but I cannot figure out WHERE and HOW to use this code:

    protected void onResume() {
    super.onResume();
    AppEventsLogger.activateApp(this);

    // …
    }

    // Optional: App Deactivation Event
    @Override
    protected void onPause() {
    super.onPause();
    AppEventsLogger.deactivateApp(this);
    }

    I got that code from this page: https://developers.facebook.com/docs/app-ads/sdk

    Where do I put that code? The lack of this final step on that page is infuriating.

  • unity button tutorial | Code goFrance!
    Posted at 19:47h, 02 June

    […] Facebook and unity tutorial – part one – paladin studios In this 3-part series we'll learn how to connect our unity application with facebook, show highscores of our friends and how to secure our application.. […]

  • karthi
    Posted at 13:38h, 18 September

    Download is not working… Kindly upload in the new link

Post A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.