How to add Facebook to Unity Android?

I searched for this before, but couldn’t find a solution that was easy or cheap (by cheap, I mean free).

Pavel Kultyshev (@getencapsulated) also wrote a blog post, sharing messages on Twitter or Facebook by following the link in the browser of a mobile device or by opening the client app on this device. I haven’t tried this approach though, because I’m looking for something more “native” to Unity.

If you’d like an easy drag and drop solution and willing to spend, then there are a couple of available plugins: the aptly named Facebook Plugin for Android by Mida Mobile (for $20), Unishare, that also includes Twitter, LinkedIn, Sina Weibo, etc. (it’s $25, I don’t know how good it is, but for 5 more dollars you get way more social stuff, sounds pretty good), and of course, Prime31 also has one, it includes Twitter too (for $65 though).

Macaronics (phardera) also wrote a blog post on how to do this using Android Plugins: (it’s in Chinese though). Don’t worry, the entire project is available in phardera’s github (

Ultimate List of Purplelilgirl Tutorials

Throughout the year(s) I have accumulated a number of mini tutorials, code bits and links, but they are just scattered in this blog like.. um.. sprinkles? And they need to be organized. So here, I am going to attempt to create a link list:




Misc. iOS and game development-related:

Book reviews and overviews:

Games, apps reviews and self-promotions:

Gamasutra blogs and reblogs:

Mini Tutorial: How to post score of your Unity iOS game to Facebook?

-without shelling out $65 😉

Well, if you have $65 to spare, just check out Prime31’s Social Networking plugin (you can even get Twitter!).


If you don’t, like 1-broke-girl/me, read on…

There are two parts to this, Unity side and Xcode side. We must find a way for Unity and Xcode to be friends and talk to one another, you know call each others’ functions, access each others’ variables etc.

First let’s take advantage of NSUserDefaults and PlayerPrefs to save some variables (you may encrypt the score variable if you are afraid of cheaters).

PlayerPrefs in Unity…

PlayerPrefs.SetString(“score”, score.ToString());

… can be read in Xcode using…

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *score = [defaults objectForKey:@”score”];

There, we know how to pass variables, what about functions…?

In order to do that, I read this tut, which is in Simplified Chinese!  ( The gist of that tutorial is that you create this other class (let’s just call it Facebook.cs):

using UnityEngine;  
using System.Runtime.InteropServices;  

public class Facebook : MonoBehaviour {

     private static extern void _PressButton0 ();  

     public static void ActivateButton0 ()  
     {  if (Application.platform != RuntimePlatform.OSXEditor)   
        {   _PressButton0 ();  

The _PressButton0() will actually call some code in Xcode (we’ll get to that).

Someone else in Unity has to call ActivateButton0, a GUI button, perhaps?

if(GUI.Button(new Rect(0, 0, 130, 235), “Facebook”))
{       Facebook.ActivateButton0();

So when the player clicks on the GUI button, ActivateButton0() will be called which will in turn call _PressButton0().

But where’s _PressButton0()?

We create a ViewController class in Xcode (let’s just call it MyView.m):

#import “MyView.h”
#import “AppController.h”

@implementation MyView

void _PressButton0()  
{   AppController *appController = (AppController*)[[UIApplication sharedApplication] delegate];

    [appController feedDialogButtonClicked];


So there’s _PressButton0()!

Now let’s do the Facebook related things. Go to Facebook’s Developer site and follow the tutorial:

Instead of putting some stuff in ApplicationDidFinishLaunchingWithIOptions… I placed everything in a function I called feedDialogButtonClicked.

– (void) feedDialogButtonClicked {
    facebook = [[Facebook alloc] initWithAppId:@”221872691249521” andDelegate:self];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@”FBAccessTokenKey”]
        && [defaults objectForKey:@”FBExpirationDateKey”]) {
        facebook.accessToken = [defaults objectForKey:@”FBAccessTokenKey”];
        facebook.expirationDate = [defaults objectForKey:@”FBExpirationDateKey”];
    if (!)
    {   ;
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSString *level = [defaults objectForKey:@”level”];
    NSString *score = [defaults objectForKey:@”score”];
    NSMutableDictionary *params =
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
     [NSString stringWithFormat: @”I just scored %@ in the %@ Level of Maru Penguin!”, score, level], @”name”,
     @”“, @”caption”,
     @”Get Maru Penguin for free in the iTunes Store”, @”description”,
     @””, @”link”,
     @”×480-75.jpg”, @”picture”,

I had a little problem with fbDidLogin (the one mentioned in the tutorial), good thing this other tutorial solved it for me:

I ended up commenting out:

    if (!)
    {   ;

Because I seem to be able to post feeds to my Facebook wall even without it (don’t know why, anyone care to explain?).

Another helpful link: How to include a link in my feed-post using FBConnect from iPhone app? ( This answer in this post explains stuff that you can include in your Feed Dialog pretty clearly.

And um, I think that is it. That bunch of codes can post your scores from Unity iOS to Facebook.

Now my other problem is, how to add a share link to the feed my app posted? Anyone, help?

Also check out an old blog post of mine about how to post pictures from Cocos2D iPhone to Facebook:


Since generated feeds don’t get the share button (I Google-d for 2 days and found nothing, at the end of it, it was a Which Avengers are You? quiz that helped me solve my problem) , do you know what I eventually did? I went back to that Cocos2D blog post and did it that way (That’s what the Avengers app did, by the way, I’m Hawkeye :D). I posted a photo of the results screen, lol, which is actually what my boss suggested in the first place. And since when you post photos, you can include captions (no advertising though), so there. Problem solved -ish.


Okay, I am apparently not a very good Googler, since only saw this today: Free, Facebook, Unity, iOS, all the keywords that I’ve been searching for, all along was in the Unity Forums!




By the way, we made an app (the one in the sample), it’s a game and it’s free and it stars a penguin named Maru in search of yummy fishies around the world (so far he only got to Asia)…


Mini Tutorial: How to add Facebook to your iOS Cocos2d game

So you want to add Facebook integration to your iOS Cocos2d game (allow players to upload screenshots, videos or post stuff to their wall, like how awesome your game is). First off, hop to the Facebook Developers website and check out the Mobile part, there should be a Getting Started page, this page:

Getting Started Mobile Apps

Follow the steps. Once you’re done with that, you pretty much already know how to post the the player’s Facebook wall.

Next question, how to upload a photo or a video. For videos, just check out a how-to blog post by Christine Abernathy. Link:

How-To: Use the Graph API to Upload a Video (iOS)

Just follow that tutorial.

For photos, just replace the video code to:

UIImage *img = [UIImage imageWithContentsOfFile: @”img.jpg”];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: img, @”picture”, nil];
[delegate.facebook requestWithGraphPath:@”me/photos”

But, but, but the samples are not for a Cocos2d project.

For a Cocos2d project it’s more or less the same.

So your AppDelegate.h will look something like this:

#import <UIKit/UIKit.h>
#import “FBConnect.h”

@interface AppDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate, FBRequestDelegate>
{    UIWindow *window;
    Facebook *facebook;

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) Facebook *facebook;
@property (nonatomic, retain) NSString *appId;


Just take note of the Facebook related stuff. I also added a NSString appId, which will store our app’s id.

Somewhere in AppDelegate.m applicationDidFinishLaunching (before you run your game scene):

facebook = [[Facebook alloc] initWithAppId: @”<APPID>”];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@”FBAccessTokenKey”]
        && [defaults objectForKey:@”FBExpirationDateKey”])
{   facebook.accessToken = [defaults objectForKey:@”FBAccessTokenKey”];
        facebook.expirationDate = [defaults objectForKey:@”FBExpirationDateKey”];

And then as mentioned in the previous examples, add this to code as well:

– (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{   return ;

When I ran my app on my device I encountered this error:

sgx error: background gpu access not permitted

So I Googled and found this link:

And it said add these lines of codes to the AppDelegate code:

– (void)applicationDidEnterBackground:(UIApplication *)application
{   [[CCDirector sharedDirector] stopAnimation];

– (void)applicationWillEnterForeground:(UIApplication *)application
{   [[CCDirector sharedDirector] startAnimation];

– (void)applicationWillResignActive:(UIApplication *)application
{   [[CCDirector sharedDirector] pause];

– (void)applicationDidBecomeActive:(UIApplication *)application
{  [[CCDirector sharedDirector] resume];

Now in your game scene, or wherever in your game that needs some Facebook thingamajigie, like when the player clicks on an upload screenshot to Facebook button: (These codes are based on the upload video tutorial)

-(void) uploadToFacebookTapped: (id) sender

{  AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (![delegate.facebook isSessionValid])
        NSArray* permissions =  [[NSArray arrayWithObjects:
                                  @”publish_stream”, @”user_photos”, nil] retain];
        [delegate.facebook authorize:permissions delegate: self];
    }   else
    {   [self uploadScreenshot];


– (void)fbDidLogin
{   [self uploadScreenshot];

{    NSLog(@”fbDidNotLogin”);

-(void) uploadScreenshot
{   AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent: @”screenshot.png”];
    UIImage *img = [UIImage imageWithContentsOfFile: path];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   img, @”picture”,
    [delegate.facebook requestWithGraphPath:@”me/photos”

So what happens is, if your player is not logged into Facebook and is using the Facebook function for your app for the first time (for that session), it will redirect the player to the Facebook app, or a web browser to allow the player to login and authorize your app. Once that is done, the fbLogin function will be called. And then uploadScreenshot.

And the call back code:

– (void)request:(FBRequest *)request didLoad:(id)result
{    if ([result isKindOfClass:[NSArray class]])
    {   result = [result objectAtIndex:0];
    NSLog(@”Result of API call: %@”, result);

– (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{   NSLog(@”Failed with error: %@”, [error localizedDescription]);

After the screenshot has been upload, request didLoad will be called, if there is some kind of error along the way, request didFailWithError will be called.

And that’s it 🙂

Plugins love ❤

  • Firefox Personas (where I got my lovely Cath Kidston theme)
  • (for streaming music from
  • Facebook (for well checking Facebook notifications, changing statuses, etc.)
  • Tumblr (for well, duh)
  • WebMail Notifier (for checking multiple email accounts)
  • Echofon (for Twitter, which I basically use like chat)
  • ReminderFox (for reminders)