unity-facebook

Accessing Facebook within Unity

October 19, 2010

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

I’ve been struggling lately to get Facebook to work inside my Unity game as I wanted to use the new Graph API and the compiled .dll had to be .NET 2.0 to work within Unity. There was also the issue of finding a good JSON library that worked with .NET 2.0 and the fact that Mono had issues accessing https via the System.Net library.

There are a lot of ways to access Facebook if you are building a game for the web player but it’s difficult if your game is desktop based as you have to somehow get the user to login to Facebook and authorize your application, this is difficult in Unity as it’s WWW class doesn’t have enough control over it nor does the launch application. I couldn’t find a solution that existed so I’ve come up with something that works perfectly, probably not-as elegant but it is a good trade-off.

Download Unity Project         Download VS Project

The above two downloads should explain all but basic usage is:

  1. Compile the above VS project and copy the FacebookAPI.dll and JsonFx.Json.dll in to your AssetsPlugins folder.
  2. You can now use it in a C# script within Unity – refer to the official C# Facebook API
  3. ???
  4. Profit!

Here’s an example C# script that you can use within Unity:

using UnityEngine;
using Facebook;

public class UFacebook : MonoBehaviour
{
	public static string MagicToken;
	
	public static string GetUserProperty(string user, string prop)
	{
		try
		{
			FacebookAPI api = new FacebookAPI(MagicToken);
			Facebook.JSONObject request = api.Get("/" + user);
			
			return request.Dictionary[prop].String;
		}
		catch
		{
			return null;
		}
    }
}

You can then do UFacebook.GetUserProperty(“eth0izzle”, “name”); in a C# or even a JavaScript file – easy :) Of course this is very basic class and can be extended for your needs.

To authenticate the user and access the API via OAuth you will need an OAuth access token which is returned in the redirect_uri as a hash tag once the user authorises your application. The issue here is how do we get the access_token back into our Unity game? Technically you can’t so we need some user intervention…

In your game project use Application.OpenURL("https://graph.facebook.com/oauth/authorize?client_id=147305235313757
&redirect_uri=http://www.ifc0nfig.com/Facebook/UnityGame/
&type=user_agent&display=page");
when the user clicks “Facebook connect”, for example. Our redirect_uri is where the magic happens, all we do is grab the access_token from the URI with some JavaScript: var access_token = window.location.hash.split('&')[0].replace('#access_token=', '');, print it to the screen and ask the user to paste it back into the Untiy game – you can take a look at the HTML source code for a better example and don’t be shy to look at how I’ve implemented this.

So what could we do with this? A game that randomly spawns AI enemies with the names of your Facebook friends and their profile picture as it’s face. A game that keeps track of the users Places and updates the game location accordingly. A game that reads what movies, books and music you like and then displays relevant ads in-game – the possibilities are endless, good luck! :-)

Tags: , , , ,

42 Comments

  1. steffan says:

    Hi manThx for tutorial- it’s really cool, but only in the unity. Cause when i’m trying create the exe file from that project it’s shows me the error:”ArgumentException: The Assembly System.Web is referenced by FacebookAPI. But the dll is not allowed to be included or could not be found.”Maybe u know what’s wrong ?Bless ya.

  2. Sargo Darya says:

    Just wanted to mention that you can do it a bit easier when using a canvas application. Use SendMessage from JS and ExternalCall from within Unity3D to request and send tokens.

  3. Penny says:

    Hi Paul,I’d like to reference this tutorial in the book I am writing about Unity. Can you email me directly so I can give you more details?ThanksPenny

    • Paul Price says:

      Hi Penny, that sounds great. You didn’t seem to leave an e-mail address though; you can e-mail me at eth0@ifc0nfig.com :-) Regards, Paul.

      • Philipp says:

        Hey Paul,I’m not writing a book, but my bachelor thesis. Just wanted to tell you, that I’m going to reference this tutorial there too ;) (only if its ok ^^)And i added it to my favourites, so i can implement it into my game as soon as the thesis is finished ;) Thank you very much!Philipp

      • Maria says:

        What I mean is more than 50% of the voting papulotion choose to support the pan-democratic, not just the banana party.For those who didn’t vote, it’s their free will to be silent. But then they also fully acknowledge that their right will be represented by those who chose not to be silent.Quite funny about your representation theory, if that’s the real way to play with, think about the following:June 4th, 1989: 5m of Hong Kong people support the Tiananmen IncidentAugust 18th, 1967: the majority of Chinese citizens support the bourgeoisie1970-1976: majority of American citizens support the Vietnam WarOctober 17th, 2012: the majority of Hong Kong people support to completely remove the Moral and National Education (fact :p )

  4. Erbomba says:

    Im using some aproach from it, and is workign perfect on Unity3D but not when I build it. Same happens when I use your project, directly.On the other hand, what if we add the Facebook.cs directly from git, Unity3D complains about the System.web…

  5. kiran patel says:

    how to post on facebook’wall of a user??

  6. John S. says:

    Just to update your instructions for anyone who has trouble finding that menu setting in the latest Unity (3.5.2f2).The setting was under Edit->Project Settings->Player. Then in the Inspector under Other Settings->Optimization->Api Compatibility Level I changed to .NET 2.0.I can confirm this builds after changing the above setting (tested windows and Android).

  7. Ahmed says:

    Thanks for this great tutorial … but can you plz upload the files or update the linksi want to download them but i couldn’t , thanks in advance ..

    • eth0 says:

      Hi Ahmed, thanks for letting me know. I’ve had a few issues with my hosting provider and I’ve switched twice in the last few weeks. The files are there now.

  8. Fabio Macedo says:

    Hi,I download your project, and i aplied some modifications.So when I click in “facebook button” I publish a message in my wall.There is the codo to do it:FacebookAPI api = new FacebookAPI(MagicToken);api.AccessToken = MagicToken;static Dictionary postDetails= new Dictionary()postDetails["message"] = “TESTE MESSAGE TO POST IN MY WALL”;api.Post(“/me/feed”, postDetails);(it’s work perfectly, so my problem is when I triy to publis a photo on my album. The same logic I use:Dictionary args = new Dictionary();args.Add(“message”, “sssssss”);args.Add(“source”, “url-my-image.jpg”);pi.Post(“/me/photos”, args);( and it doesn’t work…)any sugestion how i publish to a album using that sdk????I try also using:FacebookMediaObject facebookUploader = new FacebookMediaObject{FileName = “url-my-image.jpg”,ContentType = “image/jpg”};but when i try to passit to a api.post(….) it isn’t possible because it recive a Dictionary() and not a Dictionary()Need help….

  9. jovs says:

    hi i tried your project, and it seens the application is already deleted in facebook?do you have any suggstion on how work on this?really need your help.thanksheres the error after clicking on the facebook button{“error”: {“message”: “Error validating application. Application has been deleted.”,”type”: “OAuthException”,”code”: 101}}

  10. rian says:

    hi is there any you can send me a sample of using unity connecting to facebook?really need it badly, thanks in advanced.

    • Paul says:

      Hi Rian, did you try and download the sample project linked in the article?

      • rian says:

        hi paul is there any way, we can run the application without entering the token?which somehow integrated already in the code.thanks

        • Paul says:

          Possibly. I intend to rewrite this article and try and use the browser plugin for Unity so you can approve the Facebook application in-game without copying tokens, etc. Keep a look out :-)

          • rian says:

            hi its nice to hear paul, looking forward to that,amazing….

          • Hey Paul,Any update on the revamped article which includes login through the built in browser?Also, any thoughts on how to make this work with the WWW class exposed in Unity?CheersSpencer

          • Paul says:

            Hi Spencer, I had a quick look at various browser plugins for Unity and I think (it was a while ago) they all required Pro versions of Unity. I remember coming across one that didn’t work and spent hours trying to get it to work and optimize it so it wasn’t ridiculously slow, I gave up in the end though :( .The WWW class will not work in this case as it requires user interaction. You could probably use the WWWForm classes to do a HTTP POST to the Facebook login page but that requires you to ask for the users Facebook username/password which I doubt any one will give up and not to mention it’s highly against the Facebook ToS.I’ve been out of the Unity scene for a while but I believe this is still the best way to login with Facebook and a pure desktop game.

        • Paul says:

          Good news. Check out my latest post http://www.ifc0nfig.com/accessing-facebook-unity-game-2/ – you don’t have to copy/paste access tokens :)

          • Sara says:

            السلام عليكم ورحمة الله وبركاتهحاولت أن اتوقف عن تحميل الألعاب من ستيم مؤقتا بسبب كثرة شكاوي أإخواني ولومهم لي بإستهلاك السرعة. وكذلك توقفت عن اللعب أونلاين لان السرعة بطيئة مما يجعل الإستمتاع بالألعاب سيءالسؤال هنا .. مع وجود السياسة الجديدة التي تدّعي أن هناك أشخاص يستهلكون أكثر من المستوى الطبيعيهل الإنترنت مباع على أنه لشخص واحد أو لمنزل واحد؟اشتراكي هو أشتراك منزلي فالإجابه واضحه .. والثاني هل في المنزل الواحد شخص واحد يستخدم الإنترنت ؟في منزلي يتعدى إستخدام الإنترنت الـ 15 جهاز من اجهزة حاسوب وهواتف نقالة وأي بود والـ بلي ستيشن وأيضا السرعة المتاحة إلى منطقتي هي 2 ميجا وإن وجدت خدمات لتحسين هذه السرعة فهي مكلفة.بالرغم من أن أغلب هذه الأجهزة تستخدم الانترنت بشكل عادي أو لا تكون جميعها متصلة بنفس الوقت ما زال سقف الاستهلاك للتحميل يصل إلى حدوده قبل نهاية اليوم بعد تنزيل سرعة الأنترنت إلى الربع .. يصبح الإنترنت غير قابل للإستخدام بسبب العدد الكبير.The Speed limit our ISPs provided don’t fit the cerrunt year needs. for example:-A free to play game from Steam (team fortress 2) cost almost 10GB in space.and if you got the game, my experience here is not even a 2mb speed allowing the game to be playable online. probably because i am not the only one who’s using the internet. * did the cap consider how many person using the internet at each resident?* does they (the ISP) have what prove that only 5% of people are effected by the cap?is that 5% of the users are full families?* why does they allow people to buy there internet in full prices if they will not give them what they paid for because the FAP system.*** wouldn’t it be more fare to have agreement between theme and those people who they are taking (more like stealing) there bandwidth from.in another note, even thought i subscribed in a 2mb residential normal DSL service, 83% of the time we(me and my family) are using a 512kb service.

  11. Andrew says:

    Do you know if you script works in a Mac Standalone build? I was trying to implement it for both Windows and OS X. The Windows version works fine but the Mac one doesn’t seem to talk to Facebook after I give it the access code. I was thinking it might be the JsonFx Library since I read other people having issues with it on a Mac Platform. Do you think it would be possible to switch it out with something like MiniJSON and still have FacebookAPI function correctly?Thanks in advance.

  12. Joshua says:

    hello!I am new in developing Unity 3D video games, I just want to make an example of how to post a score to facebook, but so far I have not managed to post a string can help me =) thanks.shirohigue@gmail.com

  13. NeroShiny says:

    Hi paul, where i find the HTML what you use in the example???Sotty for my bad english

  14. NeroShiny says:

    Hi paul, how igrab the access_token from the URI with some PHP Or could you send me the code you use for that?

  15. Cosmin says:

    Is the website that shows the magic token not working anymore?I have added my appId and change the web player properties accordingly, but the page that displays the magic token doesn’t work.

    • Tofiq says:

      Thank all of you and this is definitely the best online drawing tool I ever used. I told all my friends to use it, and they’re all very happy to know this. expecting for the android version ^_^

  16. chamnab says:

    {“error”: {“message”: “Invalid redirect_uri: Given URL is not allowed by the Application configuration.”,”type”: “OAuthException”,”code”: 191}}i got this error , can you help me ?

    • sevans says:

      @chamnab – You need to enter a site url into your settings on the facebook developer dashboard. Website with Facebook Login.1) go to the following URL and login if need behttps://developers.facebook.com/apps/Now hit Edit app2) open the Website with Facebook Login section3) enter this site URLhttp://www.ifc0nfig.com/Facebook/UnityGame/&type=user_agent&display=page4) hit save changes then wait a few minutes5) try it out

      • sevans says:

        The page appears to be broken, but you should be able to snag the access token from the url as it attempts to load the page. Just look for access_token=copy that part out and paste it into the box.I got it working by doing that.

  17. One more question… Any chance this would work on iOS? My hunch is that it wouldn’t.Thanks!

    • Paul says:

      Hey Spencer, I’ve not got an iOS device to test with but I see no reason why it wouldn’t. I believe the code to launch the browser in Unity will launch Safari on your iOS device – give it a go :)

  18. Cristiano says:

    Hello, someone tried to export to flash? I tried and I returned this error:ArgumentException: The Assembly System.Web is referenced by FacebookAPI. But the dll is not allowed to be included or could not be found.UnityEditor.AssemblyHelper.AddReferencedAssembliesRecurse (AssemblyPath System.String, System.Collections.Generic.List `1 alreadyFoundAssemblies, System.String [] allAssemblyPaths, System.String [] foldersToSearch, System.Collections.Generic.Dictionary` 2 cache) (at C :/ BuildAgent/work/14194e8ce88cdf47/Editor/Mono/AssemblyHelper.cs: 72)UnityEditor.AssemblyHelper.AddReferencedAssembliesRecurse (AssemblyPath System.String, System.Collections.Generic.List `1 alreadyFoundAssemblies, System.String [] allAssemblyPaths, System.String [] foldersToSearch, System.Collections.Generic.Dictionary` 2 cache) (at C :/ BuildAgent/work/14194e8ce88cdf47/Editor/Mono/AssemblyHelper.cs: 75)UnityEditor.AssemblyHelper.FindAssembliesReferencedBy (System.String [] paths, System.String [] foldersToSearch) (at C :/ BuildAgent/work/14194e8ce88cdf47/Editor/Mono/AssemblyHelper.cs: 107)UnityEditor.HostView: OnGUI ()The API also flash does not work.Using the WWW class works, export to flash, but so far only managed to upload profile picture with this reference:http://answers.unity3d.com/questions/318060/has-anyone-had-success-with-facebooks-graph-api-in.htmlAnyone know a way to export to flash a system to connect to facebook using Unity3D?Thank you!

  19. [...] my old post I shown you how to authorize a user via Facebook and access the Facebook API in your desktop Unity [...]

  20. Kranthi says:

    Hi There,Is there any chance to use this code in Unity android application?Thanks in advance,Kranthi

Leave a Comment