Accessing Facebook within your Unity Desktop Game – Round 2

August 11, 2013

In my old post I shown you how to authorize a user via Facebook and access the Facebook API in your desktop Unity game. Unfortunately this involved the user to copy and paste an access token from their browser in to your game. Well now I’ve revisited this and made it fully automated with a nice smooth process.

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

Here’s how it works:

  1. User clicks “Login with Facebook” in the game
  2. We fire up the users browser (via Application.OpenURL())) to a Facebook login prompt, passing along a uniquely generated id.
  3. The user logs in with Facebook and accepts any app permissions requested. They are then redirected to a page on your server so we can grab the access token and unique id – this is then persisted in memory or a database.
  4. Meanwhile, our game is constantly polling a specific URL which checks for an access token stored against that unique id. If the server responds back with an access token then the user has logged in.
  5. We get said access token from the server and use it to make API calls.

And here’s a video of it in action:

I’m not going to create a tutorial on how to achieve this as I believe code speakers louder than words. In the project below you’ll find a sample Unity scene, a modified version of the Facebook C# SDK and a basic ASP.NET MVC website to handle the token exchange. Check it out, use it how you wish and if you have any questions drop me a comment below.

Download Project

Hosted Service (via http://apify.ifc0nfig.com/ufb)

To handle the token exchange between your Unity game and the users browser you will need a web service. I have included the source code for my example in the zip above and would recommend running your own service. However, if you’re just experimenting with Unity and want to get something up and running quickly or creating a small game between friends and still want to offer Facebook integration I’ve created a hosted service which is very easy to use:

  1. Download the above project zip and open up the script UFacebook2.cs
  2. Change the _redirectEndpoint property to point to http://apify.ifc0nfig.com/ufb
  3. If you need to request any additional Facebook permissions use the &scope= query string in the Facebook redirect URL (on the Application.OpenURL() line)

And that’s it! You’ll get returned an access token which will be valid for 60 days from the time of issue, use this token to make requests against the Facebook API as shown in my example. Once the token has expired make sure to push your user through the same flow to get a new token. If you have any suggestions please let me know.

Please note the tokens are persisted in memory and removed once retrieved by your Unity game thus you should save them client-side.

Tags: , ,


  1. [...] an updated version check this post out. It’s fully automated and no longer requires the user copy access [...]

  2. samim says:

    any clues on how to set up the app in facebook dev center to work with localhost?

    • Paul says:

      You just need to add localhost to your “App Domains” and set the “Website with Facebook Login Site URL” to your local webserver.

    • Alana says:

      Yesterday I read The List by Melanie Jacobson. It is a quick read, a sweet little rnmcoae but so cute! The main two characters are so witty, I kept laughing out loud at their banter back and forth. It was a perfect, Sunday afternoon, chill out book to read.

  3. samim says:

    I´m assuming you need to run a php script on your local server to fetch the facebook access token? Any chance you could post that bit? I´m having trouble getting “SerializationException: Invalid JSON string”.Tried a bunch of php script that return the token but nothing works so far.

    • Paul says:

      Everything you need is in the above zip. The “script” is written in C# using the MVC framework but you could easily port it over to PHP, take a look inside the “WebFacebookLoginReceiverControllersFacebookController.cs” file.Essentially you’re storing the generated token and Facebook access token in memory (or database) so that the Unity client can grab it.

    • Malaika says:

      I just finished “Hotel on the Corner of Bitter and Sweet” by Jamie Ford. It’s an ideicnrbly beautiful book. Lots of anachronisms but it doesn’t matter because it is so nice to read. The one before that was “Beautiful Assassin” by Michael C White. It is so fantastic and a very interesting read I couldn’t put it down!

  4. samim says:

    Ah i see. I´m rusty as hell in PHP but will see if i can convert this somehow.

    • Paul says:

      I contemplated setting this up a service so all you (and other developers) would have to do is point their Unity game to my endpoint and the rest will magically happen – would you be interested?

  5. samim says:

    would be interested very much! please keep me posted. In the mean time i´m php hell ;-)

  6. samim says:

    wow you are amazing, that is cool stuff – thank you!i´ve setup your url in the script and configured the facebook app to point to your endpoint.now getting this error:(OAuthException – #100) Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request

  7. Samim says:

    Great stuff, works like a charm!Very useful for a quick facebook Login in your pc/mac game!Never the less i guess I´m forced to set up my own endpoint now as i need facebook permission for additional graph items. Or did i miss something in that regard?

    • Paul says:

      Nope, just append &scope={perms} on the Application.OpenURL() line, e.g:Application.OpenURL(String.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&state={2}&scope=user_events", _facebookAppId, _redirectEndpoint, token));

      • Hanane says:

        He’s doing pretty well, aulcatly. The greatest feat was stopping the economy from going completely in the toliet. Had he followed the Republicans’ advice to constrict the dollar, we would be in a depression right now, not recovering from a recession. The Republicans’ decisions to fight two wars and not pay for them, and their decisions to deregulate everything in sight, have been costly. Fortunately, the economy is slowly turning, and we don’t have to live with previous mistakes any longer.And unlike the first year of the Bush Administration, the first year of the Obama Administration hasn’t seen any successful terrorist attacks on U.S. soil. The system broke down on Christmas Eve as it did many times after 9-11 but instead of reacting with emotion and naivete, this President chose analysis and reason to try and fix the problem. Previous management chose emotion and lawlessness.He has tried to fix our health-care system, which everyone agrees is broken. He has engaged the Muslim world, which is vital to our national security. He has made green technology a priority, which is vital for so many reasons. And he has taken a thoughtful, intelligent approach that is appreciated by our allies.Obama isn’t perfect and to compare him to Bush sets the bar extremely low. I wish he would’ve made more of a public-option push, and had a little more of W’s certitude and Dick Cheney’s school of GFY . He does come off as a little too professorial. But given the garbage he inherited, he’s doing OK. And getting better all time.(I still think if Palin gets the nomination, Obama might win every state. Even Alaska.)

  8. Samim says:

    Perfect, all works like a charm!Here is an permissions example, maybe useful for others:Application.OpenURL(String.Format(“https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&state={2}&scope=” +”email,” +”user_about_me,” +”user_birthday,” +”user_hometown,” +”user_interests,” +”user_likes,” +”user_location,” +”user_photos,” +”user_questions,” +”user_relationships,” +”user_relationship_details,” +”user_religion_politics,” +”user_status,” +”user_videos,” +”user_website,” +”user_work_history,” +”read_stream”, _facebookAppId, _redirectEndpoint, token));

  9. Monni says:

    I’m getting an error: DllNotFoundException: MonoPosixHelper
    System.IO.Compression.DeflateStream..ctor (System.IO.Stream compressedStream, CompressionMode mode, Boolean leaveOpen, Boolean gzip)

    does anyone know how to fix this or what causes it?

    thank you

  10. aditya says:

    hi when i tried to play it , when browser open it show

    “error”: {
    “message”: “Invalid redirect_uri: Given URL is not permitted by the application configuration.”,
    “type”: “OAuthException”,
    “code”: 191

    help :(

  11. João says:

    The project download link is not working! Could you fix it?
    Thank you

  12. Chris says:

    My PHP is really rusty too. Has anybody created the PHP service?

    Would be great to share if any PHP genius has achived it!

Leave a Comment