Integrating Unity to Facebook. Authorization and news sharing

Who wants to make their game more viral? Welcome to the 2nd part of Integrating Unity to Facebook series. I promise there will be some more code this time.

Plan:

  1. Integrating Facebook SDK
  2. Authorization and news sharing (reading now)

Disclaimer. Just like the rest of my articles, this one can include some non-optimal choices so if you’d like to point out some better solutions, by all means, do so in the comment section below — I will be glad to hear from other Unity developers.

Even though the steps can differ depending on the type of your project, basics of how to integrate Unity with Facebook are best described in the official documentation. So once again, go check it before you start. I hope that you have already integrated Facebook SDK in your project (if not — integrate Facebook in Unity or you won’t be able to follow along) and we have only a couple of things to do :)

Oh, I almost forgot. Why Unity-Facebook integration? It’s pretty simple. Social component is a very powerful one and when using it right, you can get a fair amount of new players. After all, we all want more people to enjoy our games!

Treasure Pop Bubble Shooter and City Jumper — Level complete

Integrating Sharing Logics

Several approaches are used for integrating sharing logics into the gameplay. Usually we provide such function after the player has completed a level or some other logical part of the game. In this case the player can check his or her progress so far and share it with friends (think about all those posts in social networks that appear after successfully passed exams or university graduation).

Here the game designer is sort of pulling the strings of the player who doesn’t mind sharing his gaming achievements. Besides, you can motivate players by doubling gold/rings/mushrooms or other collectibles available in your game, thus receiving a few reposts.

Another option for generating re-posts is to give money to the user. In-game currency, I mean (otherwise you’d have to change your monetization model :). And by limiting the number of reposts you can get a constant flow of them. Not so bad, right?

Treasure Pop Bubble Shooter and City Jumper — Share with friends and get coins

Initializing SDK

Before reposting you need to initialize SDK. Add the following to the Awake() method of the object component in your splash scene (or any other base component that implements MonoBehaviour):

void Awake (){if(!FB.IsInitialized){// Initialize the Facebook SDK
        FB.Init(InitCallback, OnHideUnity);}else{// Already initialized, signal an app activation App Event
        FB.ActivateApp();}}privatevoid InitCallback (){if(FB.IsInitialized){// Signal an app activation App Event
        FB.ActivateApp();// Continue with Facebook SDK// ...}else{
        Debug.Log("Failed to Initialize the Facebook SDK");}}
 
privatevoid OnHideUnity (bool isGameShown){if(!isGameShown){// Pause the game - we will need to hideTime.timeScale=0;}else{// Resume the game - we're getting focus againTime.timeScale=1;}}

Excellent! Now we have a choice and can write what we want.

Adding Repost Feature

Let’s say you’d like to add a repost feature to your app. There are two possible ways to do it. Let’s look at the first option:

FB.ShareLink();
 
 FB.ShareLink(new Uri("https://developers.facebook.com/"),
                callback: ShareCallback);

Facebook recommends using it for sharing links to various websites. It automatically gets the name of the page, description and a picture — you don’t have to worry about a thing.

Your second option for implementing the repost feature:

FB.FeedShare()
 
FB.FeedShare(
            toId:"",
            link:new Uri("https://developers.facebook.com/"),
            callback: ShareCallback);

Just like the first option it allows to share a link. But here we get a little bit more functions, even though guys from Facebook recommend to use FB.ShareLink() by default. So how does this option differ from the first one?

  1. When using it you aren’t required to post a link, you can simply use an image with title and description.
  2. It has a “to” parameter that defines on which page the publication will appear: on a user’s or on someone else’s.

Apart from it, both accept callback for processing the results of news sharing as the last parameter:

privatevoid ShareCallback (IShareResult result){if(result.Cancelled||!String.IsNullOrEmpty(result.Error)){
        Debug.Log("ShareLink Error: "+result.Error);}elseif(!String.IsNullOrEmpty(result.PostId)){// Print post identifier of the shared content
        Debug.Log(result.PostId);}else{// Share succeeded without postID
        Debug.Log("ShareLink success!");}}

t should be noted that for using this feature you DON’T need to make the user login.

But if you’d like to, see an authorization methods below. There’re two types of authorization: to read and to write.

To read:

publicvoid LoginWithReadPermission(){
        var perms =new List<string>(){"public_profile", "email", "user_friends"};
        FB.LogInWithReadPermissions(perms, AuthCallback);}

To write:

publicvoid LoginWithPublishPermission(){
        var perms =new List<string>(){"publish_actions"};
        FB.LogInWithPublishPermissions(perms, AuthCallback);}

Callback for processing authorization results:

privatevoid AuthCallback(ILoginResult result){if(FB.IsLoggedIn){// AccessToken class will have session details
            var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;// Print current access token's User ID
            Debug.Log(aToken.UserId);// Print current access token's granted permissionsforeach(string perm in aToken.Permissions){
                Debug.Log(perm);}}else{
            Debug.Log("User cancelled login");}}

When authorizing to write the user first see a usual authorization window and then a window with a request to post on the wall or send private message to friends.

Treasure Pop Bubble Shooter — Getting permissions

It means that even when using LogInWithPublishPermissions() you can get an authorized user without writing permission (if he or she cancel publishing during authorization or turn it off later on Facebook). In this case you can get all provided permissions in the following collection:

foreach(string perm in AccessToken.CurrentAccessToken.Permissions){// log each granted permission
    Debug.Log(perm);}

You might ask: why do we need that login at all? Apart from getting the obvious things like a profile picture, email, friends list etc, when using withPublishPremissions to login we can write on the user’s wall right from the app (maybe even skip confirmation step if the user allowed you to publish without confirmation).

That’s how messages about passing the next Candy Crush level appear in your news feed. But it’s a topic for a separate article :) And, as you might’ve guessed, I encourage you to leave comments below and share your own experience.

“So long and thanks for all the fish”

Need MVP development, iOS and Android apps or prototyping? Check out our portfolio and make an order today!