05-07 03:51
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

Facebook and Unity Tutorial – Part One 본문

CG & Video Games/Unity 3D

Facebook and Unity Tutorial – Part One

cinema4dr12 2013. 6. 14. 18:45

Original Web Address: http://www.paladinstudios.com/2011/11/15/facebook-and-unity-tutorial-part-one/

Introduction

A note before you start: This is a Unity tutorial about implementing Facebook in Unity projects. It’s a technical how-to guide for Unity developers who want to use Facebook Connect in their web-apps. If that sounds interesting, read on! If it does not, you shouldcheck this out

Paladin’s games allow players to play with their friends, using  Facebook. In this 3-part series we’ll learn how to connect our Unity application with Facebook, show highscores of our friends and how to secure our application.

Warning! Tech up ahead, this is not for the feint of heart!

In this introductory post we’ll create a FB application, use the Javascript SDK to retrieve the current user’s friends and display their name in Unity. This task requires some familiarity with webdevelopment, and good understanding of Unity and C#. A sneak preview of the final game we’ll be making can be viewed here.

Setting up your application and development environment

To get started, register your application over at Facebook. Do note you need to have a “developer account”, which means you have to supply your phone number. After creating your application you have to tell Facebook its a webpage, by clicking on Website at Select how your  app intergrates with Facebook. For now you can set your Site URL to http://localhost/. This allows you to test your application locally. Another notable setting is Sandbox mode, in the Advanced tab. When this is on only developers can view the application, this is useful when developing the application. Dont forget to turn it off though!

Because we want to develop locally, we want to run a webserver on our own machine. If you dont have one installed, you can use a simple package likeWampserver or XAMPP. Ensure your webserver is working properly by visiting http://localhost in your browser. We at Paladin mainly use PHP for our backend, but if you feel more comfortable using any other technology (ASP, RoR etc) feel free to use that.

Exploring the Facebook SDK

Now we have that setup, lets play around with the Facebook API. To familiarise ourselfs with the Facebook Graph lets create a sample page that gets all information we want. Facebook works using Graph which allows easy access to all information of a user, as long as he is logged in and has granted you enough permissions. We strongly encourage you to read the documentation thoroughly. We’ll be using the Javascript SDK, you should read through the documentation. For our sample we want to get the current user’s id and name, and his friends. Create an html page in your www-root with the following contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<div id="fb-root"></div> <!-- Required by Facebook -->
 
<script type='text/javascript'>
 
    //Fired when the facebook sdk has loaded
    window.fbAsyncInit = function()
    {
        FB.init(
        {
          appId      : '171298766297727',
          status     : true, // check login status
          cookie     : true, // enable cookies to allow the server to access the session
          oauth      : true, // enable OAuth 2.0
          xfbml      : false // dont parse XFBML
        });
 
        //Get the current login status.
        FB.getLoginStatus(function(loginStatusResponse)
        {
            if(loginStatusResponse.authResponse) //There is an authresponse, the user is already logged in and authenticated
            {
                logUserName();
                logFriends();
 
            } else { //The user was not logged in, allow him to.
                FB.login(function(loginResponse)
                {
                    if(loginResponse.authRespsonse) //Did he login successfully?
                    {
                        logUserName();
                        logFriends();
                    }
                });
            }
        });
 
        function logUserName() //When we are logged in this shows our name.
        {
            FB.api('/me', function(meResponse)  //Do a graph request to /me
            {
                alert(meResponse.id + " " + meResponse.first_name); //Show the response
            });
        }
 
        function logFriends()   //When we are logged in this shows our friends.
        {
            FB.api('/me/friends', function(friendResponse) //Do a graph request to my friends.
            {
                for(var i = 0; i < friendResponse.data.length; i++) //Loop over all my friends
                    alert(friendResponse.data[i].id + " " + friendResponse.data[i].name);
            });
        }
 
    };
 
    //Load the Facebook JS SDK
    (function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
    }(document));
 
</script>

After loading the Facebook library it will check the current user’s login status, and offer a login if he isnt already. When we’re sure we are logged we use the graph request to /me to get information about the current user. Then we request the user’s friends by doing a request to /me/friends. Use a Javascript Debugger such as Firebug and step through the code to understand how it works, and what responses the Facebook api requests give.

Bringing it to Unity

Now we have the information we want in our webpage, lets pass it on to Unity! Unity’s excellent reference manual describes how to send basic messages from and to your game. Lets create a button that will ask the HTML page to get the facebook info. Create a new Unity project and create a new script called FacebookManager. Add the following code:

1
2
3
4
5
6
7
void OnGUI()
{
    if (GUI.Button(new Rect(10, 10, 100, 24), "Get info"))
         Application.ExternalCall("GetCurrentUser")
    if (GUI.Button(new Rect(10, 44, 100, 24), "Get friends"))
         Application.ExternalCall("GetUserFriends")
}

When the user clicks the button the Javascript function GetCurrentUser is called, simple as that. We already know how to get the information from Facebook, now all we need to do is pass it on to our game. We do this by calling SendMessage to the proper GameObject and Method.  There is however a drawback, SendMessage only supports sending a single parameter to Unity, which is insufficient because we want to send a user’s facebook id and name. Therefore we have to come up with some format to pass both parameters. For larger data structures i’d strongly recommend using JSON, and interpeting it in your game. However, since this is a simple sample, we’ll just come up with our own format as such:

id,name; id, name;

Lets rewrite our basic page into something we can use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<div id="fb-root"></div>
 
<script type='text/javascript'>
 
    //Fired when the facebook sdk has loaded
    window.fbAsyncInit = function()
    {
        FB.init(
        {
          appId      : '171298766297727',
          status     : true, // check login status
          cookie     : true, // enable cookies to allow the server to access the session
          oauth      : true, // enable OAuth 2.0
          xfbml      : false // dont parse XFBML
        });
 
        //Log the user in when the page loads.
        FB.getLoginStatus(function(loginStatusResponse)
        {
            if(!loginStatusResponse.authResponse) //Not logged in, log him in
                FB.login();
        });
 
        function GetCurrentUser() //When we are logged in this shows our name.
        {
            FB.api('/me', function(meResponse)  //Do a graph request to /me
            {
                var fbdata = meResponse.id + "," + meResponse.first_name; //As per our format, 'id,name;'
 
                getUnity().SendMessage("FacebookManager", //Game object name, make sure this exists!
                                        "GetCurrentUserComplete", //Method to call
                                        fbdata); //Our serialized facebook data
            });
        }
 
        function GetUserFriends()
        {
            FB.api('/me/friends', function(friendResponse)
            {
                var fbdata;
 
                for(var i = 0; i < friendResponse.data.length; i++) //Loop over all my friends
                    fbdata += friendResponse.data[i].id + "," + friendResponse.data[i].name + ';';
 
                getUnity().SendMessage("FacebookManager",
                                        "GetFriendsComplete",
                                        fbdata);
            });
        }
    };
 
    //Load the Facebook JS SDK
    (function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
    }(document));
 
    function getUnity() //Default unity functions
    {
        if (typeof unityObject != "undefined")
        {
            return unityObject.getObjectById("unityPlayer");
        }
        return null;
    }
    if (typeof unityObject != "undefined")
    {
        unityObject.embedUnity("unityPlayer", "WebPlayer.unity3d", 960, 640);
    }
</script>
 
<div id='unityPlayer'></div>

Please note additional work has to be done in case the user declines the request or graph requests fail, but that is outside the scope of the tutorial.

Now we’ve retrieved the data in our page, lets make sure we can accept it in our game. Add this to your script, and attach it to a GameObject called FacebookManager.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
private string user_id; //Facebook id
private string user_name; //User name
private Dictionary<string, string> friends; //All the users friends key = id, value = name
 
public void GetCurrentUserComplete(string fbdata) //Called by js when the userinfo was retrieved. fbdata looks like 1234,name
{
    string[] parts = fbdata.Split(',');
    user_id = parts[0];
    user_name = parts[1];
}
public void GetFriendsComplete(string fbdata) //Called by js when the friends are retrieved. fbdata looks like 1234,name;5678,name;..
{
    friends = new Dictionary<string, string>();
 
    string[] parts = fbdata.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); //we've seperated each user, now get their id and name
 
    foreach (string user in parts)
    {
        string[] userInfo = user.Split(','); //Split each user on ',' first should be id then name.
 
        friends.Add(userInfo[0], userInfo[1]);
    }
}
 
void OnGUI()
{
    if (GUI.Button(new Rect(10, 10, 100, 24), "Get info"))
        Application.ExternalCall("GetCurrentUser");
    if (GUI.Button(new Rect(10, 44, 100, 24), "Get friends"))
        Application.ExternalCall("GetUserFriends");
 
    GUI.Label(new Rect(200, 10, 200, 24), user_name); //Display name
 
    if (friends != null) //If we retrieved our friends already
    {
        float h = 10;
        foreach (var friend in friends)
        {
            GUI.Label(new Rect(200, 10 + i * 24, 200, 24), friend.Value);
            h += 24;
        }
    }
 }

The code should be fairly self-explanatory, the parsing part can be a bit tricky as it is very error prone. Any unexpected input will break your application. If you arent sure whats going on, try setting breakpoints and using our friendly Debug.Log method to make some sence of it. All our hard work leads us to this; a screen with our current name and the names of our friends:

Great, now you know how to setup your Facebook development environment, make basic calls to the Graph API and pass the response to Unity. With the knowledge you’ve gained, think you can open a post to wall dialog from unity?

This is a 3 course tutorial. If you want to learn more, check out the following parts.

Comments