Connecting to Facebook from your Unity desktop game

Connecting your Unity game to Facebook is a doddle if it is Web based and running in the Unity Web Player as you can use the official SDK. Unfortunately it’s not as easy if your game is desktop based as you have to somehow get the user to login to Facebook, authorize your application and pass back the OAuth tokens to your game.

I've come up with an elegant solution that uses a web server for the token exchange. Here’s how it works:

  1. User clicks “Login with Facebook” in your 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 web server so we can grab the access token and unique id which are then persisted server-side.

  4. Meanwhile, your game is polling your web server checking for an access token stored against that unique id. Once available, we get said access token from the server and use it to make API calls to Facebook.

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.

Download Project

Check it out, use it how you wish and if you have any questions drop me a comment below.