Unity 3D Facebook integration with Coherent UI (tutorial)

by Nick March. 25, 13 3 Comments

After our previous showcase of a minigame that opens a door, we’re continuing the series on Unity3D with Coherent UI. This time we’ve chosen a more social scenario – you’re playing a game, finally manage to kill the big bad boss that’s been troubling you and now you want to brag to your friends! Let’s see how you can add Unity 3D Facebook integration easily using Coherent UI!

Goal

Show an in-game notification when the player kills an enemy mech, take a screenshot of that glorious moment and upload it to Facebook.

Here’s a picture of the mech’s ashes after I killed it:

Unity 3D Facebook integration with Coherent UI (tutorial)
Achievement yay!

Sidenote:
If you noticed the little avatar icon in the top left corner, that’s the profile picture of the Facebook user I’ve logged in with. Before the player logs in, the Facebook logo is displayed instead. When she clicks the logo, the Facebook login page is displayed and she’s prompted to grant the sample app permission to post on her behalf. This is what the game looks like before logging in:

Unity 3D Facebook integration with Coherent UI (tutorial)
Avatar icon before logging in Facebook

After completing the login procedure, the image changes to the profile picture.

 Prerequisites

 

  • The AngryBots scene that comes with Unity3D
  • Coherent UI for Unity3D (we’ll also assume that you’ve already imported the package in the AngryBots project)

 

 Scene setup

First, we’ll have to find a mech that will act as our archnemesis and have it send a signal when it dies so we can activate the achievement logic. This is the one I chose:

Unity 3D Facebook integration with Coherent UI (tutorial)
The innocent mech that will soon find its doom

Fortunately, the mech GameObject already has a script that emits signals upon death, so the only thing we have to do is add another receiver and configure the action name. Since all the HTML content we need is displayed similar to a HUD, we’ll add a CoherentUIView component to the Main Camera and that will be the receiver of the signal. The action name can be anything meaningful for you; I went for “OnEnemyMechDeath“.

Note: you can see the last paragraph explained visually in the picture above.

We’ve got the death notification all sorted out, now we have to configure the receiver, i.e. the Main CameraGameObject. We’ve already added the CoherentUIView  component and you can see its configuration on the next screenshot:

Unity 3D Facebook integration with Coherent UI (tutorial)
Configuration of the Coherent UI View component

 

Adding logic in the Main Camera GameObject

The component in the Main Camera GameObject that will be doing the hard work is the SignalReceiver. I’ll first show you the whole code for the class and then briefly describe the methods.


The Start method does two important things: first, it enables URL intercepting on the view and second, adds a handler that processes URL requests before they are completed. The handler itself (OnURLRequestHandler) checks the requested URL and if it starts with a bogus address that we defined as a placeholder (“http://www.coherent-labs.com/sample.html”) it redirects the request to a local resource, passing all the parameters to the local URL. If you’re not sure what’s going on, here’s a sketch of the flow:

Unity 3D Facebook integration with Coherent UI (tutorial)
Login flow

That’s all that the engine script has to do for the login. The other part is done by JavaScript, which will be discussed shortly.

Next, OnEnemyMechDeath. This method is executed when the mech dies and sends a signal, as we have previously seen. It triggers the JavaScript “ShowAchievementPopup” method and takes a screenshot of the kill site. The screenshot data is collected asynchronously as this article describes so the game doesn’t hang for a bit. The sample still has noticable lag so you can apply more sophisticated methods for avoiding that. This data is then forwarded to the JavaScript “UploadImageOnFacebook” function.

The HTML/JavaScript side

We’ll start with the HTML code for the page:


There’s nothing fancy about it, it just defines the achievement element and its animation and also subscribes for various events sent by the engine.

Note: You can examine the stylesheet file at this URL if you’re interested.

The facebook.js script

 

This script does most of the heavy lifting on the JavaScript side. It provides Facebook login functionality and functions for posting messages and photos on your wall. I’ll review the initialization and uploading only, but you can check out the whole script here if you’re interested.

The first thing that the script does is checking if the user is logged in Facebook. This is done by checking the anchor portion of the page URL – if there is none, we assume the user is not logged in (not the brightest, most secure way of determining that, but it does the job for the sample :)). If the user is not authenticated, a button element is appended to the HTML body that leads to the Facebook login dialog. Upon successful login, Facebook redirects the page to the same local resource that initiated the request (as we discussed previously in the login flow part). This time the window.location.hash.length property is greater than zero and the page assumes the user is logged in.


Changing the avatar icon is done by simply subscribing to the “auth.statusChange” event using the Facebook API:


Now that the user is logged in we can finally post messages and photos on the wall. Let’s see what happens when we kill the mech! As we’ve already seen from the engine code part, the UploadImageOnFacebook JS function is called, supplying the image as a byte array and a message. That’s half the parameters we need to upload an image; the other half are the user ID and the access token that allow us to form the correct URL and we have those from the FB initialization so we’re good to go. An asyncronous request is sent and the result is logged.

If the AJAX request goes as planned, you should see your victory over machines documented 🙂

Unity 3D Facebook integration with Coherent UI (tutorial)
The screenshot posted by the Coherent Sample App

As always here’s the video of the results:

Follow Nick on Twitter: @Nikxio
Tags:
Social Shares

Related Articles

3 Comments

Leave Reply

Leave a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

  • Looking at the javascript. Comes up with an error saying unknown identifier \’FB\’. Could you please elaborate?

    Reply
  • Nick

    The FB variable comes from the Facebook API script (http://connect.facebook.net/en_US/all.js). It should be initialized after successful redirection when you log in, that\’s all.

    I\’m not sure if they changed anything on the URL since as mentioned in the article I\’m detecting it using a very primitive way 🙂 You can verify that the Facebook script is being loaded if you set a breakpoint after the \’// Logged in\’ line in the facebook.js script or just print something there.

    Reply
  • I\’m trying to do this for mobile, there\’s one thing im failing to understand, since we use the Facebook SDK we need to set up the App in Facebook Devellopers. In the App settings when choosing the plantform it must select Website and what do I put in the Website URL and Mobile URL?
    P.S. Im using Unity 3D.

    Reply