How to Integrate Facebook API in Unity3D - Iulian Tudosa - ASSIST Software - Cover photo
Hi, my name is Tudosa Iulian and I’m a Game Developer at ASSIST Software. In this awesome article, I will show you how to:
1) Integrate the Facebook API in Unity 3D;
2) Create a Facebook developer account;
3) Create your first app on Facebook;
4) Download the Facebook SDK for Unity 3D;
5) Connect the Facebook SDK with your project;
6) Create login/logout buttons; 
7) Extract your name from your app;

I hope it will be easy for you to follow the instructions in this tutorial. I tried to make things easier for you, that's why I included a lot of pictures that will help you understand better what you need to do. I want to ensure that you focus on coding your game, instead of losing time configuring APIs. 

So let’s start!

I. Download Tools
I. 1 Unity 3D Installation

→ If you already have a Unity 3D account and Unity 3D installed, skip this step!

First, go to https://unity3d.com/get-unity/download and start downloading Unity 3D. Create an account and then select the Free version. 

While Unity 3D is being installed or after it has been installed, we will go to the next step.

I. 2 Facebook developer account

Go to https://developers.facebook.com/ and create an account (if you don’t have one already). Go to the My Apps Menu like in Picture 1.

How to Integrate Facebook API in Unity 3D
Picture  1
Select Add New App.
How to Integrate Facebook API in Unity 3D
Picture 2

In Picture 2 choose a name for your app and enter your e-mail address (the e-mail address connected to your Facebook account).
Then click on the Create App ID button.

Tips: Don’t use negative words… anyway, you will receive an alert if you do something wrong here :).

Ok, now that the hardest part is done, we can go to the next step!

Now select your app from the right panel. Select Settings and then select Basic.
(My apps→ Settings → Basic)

Here you will see some information about your app. You can edit some parameters, but for now, we will minimize the page, so that we can continue with the rest of the steps in this tutorial.

I. 3 Facebook SDK for Unity 3D

Now we will need Facebook SDK for Unity 3D. 

Download the latest version. For me, it is 7.14.1 

Download the content, save the files in a new folder on your computer and after all folders have been extracted, open the Facebook SDK folder. There you will see a type of unity package file. Don’t open it yet, because we will need to open a project of Unity 3D.

II. Unity 3D
II. 1 Unity 3D configuration

Open Unity 3D, log in with your account (if you want to do this), create a 3D app (for now it doesn't matter if is 2D or 3D) and open the project. If you want to have a similar layout as mine, please check Picture 3.

How to Integrate Facebook API in Unity 3D

Picture 3

First, we must import the Facebook SDK in our empty project. Find the folder where you saved the SDK and double-click on it.

And now you should see a panel like in Picture 4.

How to Integrate Facebook API in Unity 3D

Picture 4

Click Import and wait for the SDK to be installed.

Now we must set some parameters in Unity 3D.

II. 2 Facebook configuration in Unity 3D

Up in the menu items, you will see Facebook as shown in Picture 5. Click on it and then click Edit Settings.

How to Integrate Facebook API in Unity 3D

Picture 5

How to Integrate Facebook API in Unity 3D

Picture 6

Here we must enter the app name (Facebook app name) and the app ID.

After you complete the app ID, the warning message will disappear. The next step is to create a basic UI. 

II. 3 UI elements in Unity 3D

In the Hierarchy tab, right-click and select Create Empty. And because we are good developers, we must rename this GameObject with “Facebook Manager”.

In the same tab, right-click again and select UI and create three buttons. Select each button and rename them (e.g. “btnLogin”, ”btnLogout”, and ”btnGetName”).

If you are done, wait for me to do the same…

How to Integrate Facebook API in Unity 3D

Picture 7

Voila! To see all three buttons in the game view tab, we must select btnLogin for example and click on the desired elements (e.g. like in Picture 8) to access the different positions and then use alt to drag and drop the elements.

See Picture 9 for Logout, and Picture 10 for GetName.

How to Integrate Facebook API in Unity 3D

Picture 8

How to Integrate Facebook API in Unity 3D

Picture 9

How to Integrate Facebook API in Unity 3D

Picture 10

Now the game view must look like Picture 11.

How to Integrate Facebook API in Unity 3D

Picture 11

Because we don’t like to see three buttons with the same name, we will change them. To do this, select each button in the Hierarchy tab, click on the drop-down arrow and select text. In the right panel, you will see a text tab. Change the names to "Login", "Logout", and "Name".

Now we’ve arrived at the fun part.

III. Coding
III. 1 Scripting in Unity 3D

In the Project View, select Assets. Right-click on it, and select create, then folder. Name the folder “Scripts” and double-click on it.

In the “Scripts” folder, right click on empty space and create a C# script. Name it FacebookManager and open it. I use visual studio for editing scripts.

First of all, add the libraries that are necessary for your script to work. In our case, this is what we used:


using System.Collections.Generic;
using UnityEngine;
using Facebook.Unity;
using UnityEngine.UI;

Next, you must create button variables.


public class FacebookManager : MonoBehaviour
{
    public Button btnLogin, btnLogout, btnName;

Moving on, you must initialize the Facebook API. For this, the following function is required:


 private void Awake()
    {
        if (!FB.IsInitialized)
        {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        }
        else
        {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }
    }

Then you must create these two functions: InitCallback and OnHideUnity.


  private void 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");
        }
    }

    private void OnHideUnity(bool isGameShown)
    {
        if (!isGameShown)
            Time.timeScale = 0;
        else
            Time.timeScale = 1;
    }

Cool, if you don’t have any errors, let’s start to create the login and logout functions:


  public void FacebookLogin()
    {
        var permissions = new List<string>() { "public_profile", "email", "user_friends" };
        FB.LogInWithReadPermissions(permissions, AuthCallback);
    }

If you want more permissions, check Facebook developers documents and search for what you want to use.


private void 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 permissions
            foreach (string perm in aToken.Permissions)
                Debug.Log(perm);
        }
        else
        {
            Debug.Log("User cancelled login");
        }
    }
    public void FacebookLogout()
    {
        FB.LogOut();
    }

And for your profile name, use this function:


public void GetName()
    {
        FB.API("me?fields=name", Facebook.Unity.HttpMethod.GET, delegate (IGraphResult result)
        {
            if (result.ResultDictionary != null)
            {
                foreach (string key in result.ResultDictionary.Keys)
                {
                    Debug.Log(key + " : " + result.ResultDictionary[key].ToString());
                    if (key == "name")
                        btnName.GetComponentInChildren<Text>().text = result.ResultDictionary[key].ToString();
                }
            }
        });
    }

And the last function is the Start function for our buttons:


  void Start()
    {
        btnLogin.onClick.AddListener(() => FacebookLogin());
        btnLogout.onClick.AddListener(() => FacebookLogout());
        btnName.onClick.AddListener(() => GetName());
    }
}

And now our scripts are complete. For a better understanding, you can also see how my entire script looks like (Pictures 12 and 13).

How to Integrate Facebook API in Unity 3D
Picture 12
How to Integrate Facebook API in Unity 3D
Picture 13
Enter in Unity 3D now, and select the Facebook Manager game object. Drag the script in the right panel, under transform and then drag your buttons in the correct spaces (like in Picture 14).
How to Integrate Facebook API in Unity 3D
Picture 14
III. 2 Starting project

Now start the project. When the Start project button is blue, click on the Login button. Because we are doing this project on a PC, you will receive a warning message.

Don’t panic - your code is correct! But if you want to create another project in Android or iOS, you will see the same warning in the editor, but not on the final build.

So now, we must complete the User Access Token input tab. For this, you must click on the Find Access Token button. Then click on the button on the right of the User Token field, and copy the string and put it in Unity. After this, click on the Send Success button.

Now click on the Name button. The final view should be like Picture 15:

How to Integrate Facebook API in Unity 3D

Picture 15

Now you can sleep tonight without any worries. Good job! :)

IV. Conclusion

If you want to learn how to share, invite, get a friends list and much more, subscribe to our YouTube channel and like our Facebook page to keep up with our latest tutorials and company news.

I hope that my article about Unity 3D was useful to you and you enjoyed it!

P.S. In 2019, I will create a series with tutorials about how to create a game in Unity 3D. So, stay tuned!

Share on:

I have read and understood the ASSIST Software website's Terms of Use and Privacy Policy.

Want to stay on top of everything?

Get updates on industry developments and the software solutions we can now create for a smooth digital transformation.

Frequently Asked Questions

1. Can you integrate AI into an existing software product?

Absolutely. Our team can assess your current system and recommend how artificial intelligence features, such as automation, recommendation engines, or predictive analytics, can be integrated effectively. Whether it's enhancing user experience or streamlining operations, we ensure AI is added where it delivers real value without disrupting your core functionality.

2. What types of AI projects has ASSIST Software delivered?

We’ve developed AI solutions across industries, from natural language processing in customer support platforms to computer vision in manufacturing and agriculture. Our expertise spans recommendation systems, intelligent automation, predictive analytics, and custom machine learning models tailored to specific business needs.

3. What is ASSIST Software's development process?  

The Software Development Life Cycle (SDLC) we employ defines the stages for a software project. Our SDLC phases include planning, requirement gathering, product design, development, testing, deployment, and maintenance.

4. What software development methodology does ASSIST Software use?  

ASSIST Software primarily leverages Agile principles for flexibility and adaptability. This means we break down projects into smaller, manageable sprints, allowing continuous feedback and iteration throughout the development cycle. We also incorporate elements from other methodologies to increase efficiency as needed. For example, we use Scrum for project roles and collaboration, and Kanban boards to see workflow and manage tasks. As per the Waterfall approach, we emphasize precise planning and documentation during the initial stages.

5. I'm considering a custom application. Should I focus on a desktop, mobile or web app?  

We can offer software consultancy services to determine the type of software you need based on your specific requirements. Please explore what type of app development would suit your custom build product.   

  • A web application runs on a web browser and is accessible from any device with an internet connection. (e.g., online store, social media platform)   
  • Mobile app developers design applications mainly for smartphones and tablets, such as games and productivity tools. However, they can be extended to other devices, such as smartwatches.    
  • Desktop applications are installed directly on a computer (e.g., photo editing software, word processors).   
  • Enterprise software manages complex business functions within an organization (e.g., Customer Relationship Management (CRM), Enterprise Resource Planning (ERP)).

6. My software product is complex. Are you familiar with the Scaled Agile methodology?

We have been in the software engineering industry for 30 years. During this time, we have worked on bespoke software that needed creative thinking, innovation, and customized solutions. 

Scaled Agile refers to frameworks and practices that help large organizations adopt Agile methodologies. Traditional Agile is designed for small, self-organizing teams. Scaled Agile addresses the challenges of implementing Agile across multiple teams working on complex projects.  

SAFe provides a structured approach for aligning teams, coordinating work, and delivering value at scale. It focuses on collaboration, communication, and continuous delivery for optimal custom software development services. 

7. How do I choose the best collaboration model with ASSIST Software?  

We offer flexible models. Think about your project and see which model would be right for you.   

  • Dedicated Team: Ideal for complex, long-term projects requiring high continuity and collaboration.   
  • Team Augmentation: Perfect for short-term projects or existing teams needing additional expertise.   
  • Project-Based Model: Best for well-defined projects with clear deliverables and a fixed budget.   

Contact us to discuss the advantages and disadvantages of each model. 

1. Is ASSIST Software a reliable company for custom engineering?

Absolutely. Our partners have given us great recommendations and reviews, leading us to win The Manifest Award for Most Reviewed Software Developers. Further proof comes from our 97% employee retention rate and ongoing client partnerships for over 8 years.  

2. Are the ASSIST Software Romanian software engineers certified?

Yes. 85% of our software programmers are certified.  

At a company level, ASSIST Software is certified and recognized by industry players such as Microsoft, AWS, Google Cloud, Adobe, Drupal, Fujitsu, ISTQB, and others.  

Our employee certifications are tremendously important as they reflect the shared commitment to long-term growth.

3. Why should I choose Romania for custom software development? 

Romania has become a significant player in custom software development, attracting businesses worldwide. Romania boasts the highest number of certified IT specialists in Europe and ranks sixth globally, surpassing even the US in tech specialists per capita.  

At ASSIST Software, what sets us apart is our team and our location: our engineers are certified, experienced, and flexible, while being in the +2 GMT time zone allows us to easily facilitate meetings with clients all over the world.

4. What team will work on my project, and where will it be located?

ASSIST Software's headquarters is in Romania, a prime country for software development outsourcing. Our 350+ software engineers speak English and have a deep passion for innovation.  

We provide regular project updates through reports, meetings, and online dashboards. Generally, you'll have access to a dedicated project manager who will be your point of contact for any questions or concerns.  

5. How much will my project cost me?

Our prices are competitive, and as per our working model, we guarantee you will be satisfied with the result. Frequent meetings, check-ins, and a great communication structure will ensure this outcome.   

Project costs depend on various factors, including complexity, scope, required technologies, and team size. We'll gather detailed information about your project during the initial consultation to provide a customized quote and we guarantee that you will be able to see the benefits of bespoke software.  

1. What technologies do you work with?

ASSIST Software tackles your projects with a robust tech stack. We build native and cross-platform mobile apps, craft user-friendly web experiences, and create stunning visuals. 

Our wide-ranging expertise starts from Java, Python, and JavaScript frameworks to cutting-edge solutions like AR/VR, blockchain, and AI/ML. We also manage databases, leverage cloud platforms, and ensure flawless project execution. We're your one-stop shop for exceptional software development from concept to deployment. You can view our expertise for more details.   

2. Are you experienced in AI/ML development?

Yes. We have extensive experience in data engineering and machine learning operations (MLOps). We can employ neural networks, computer vision, and AI models to benefit your ideas.   

You can trust our long-term experience with big data, NLP, and sentiment analysis, as over the past three years, we led a European security project with 15 partners focused on detecting radicalization on social media and the dark web.

3. Do you have a research and development department and work on European Projects?

We know R&D is crucial for businesses to stay competitive and thrive in dynamic markets. Successful R&D efforts lead to developing exceptional products or services, improved efficiency and effectiveness in operations, and enhanced market positioning.   

We have established solid partnerships with 160+ European research companies, universities, and research centers (e.g., Fraunhofer, TWI, University of Heidelberg, REWE Group, SINTEF, etc.) and have participated as technical partners in over 25 EU-funded projects.  

4. Besides custom software solutions, what other services do you offer?

  • Design Thinking for Breakthrough Products:  

    We craft user experiences that resonate. Our design process is an immersive collaboration, starting with workshops to uncover your vision and user needs. We conduct market research, analyze the competition, and guide you toward cutting-edge solutions in accordance with your business requirements.  

  • Digital Transformation to Reimagine Your Business:

    Digital transformation is nothing less than a strategic shift. We empower you to become more agile and data-driven, optimizing core processes for the digital age.  

  • Scale with Confidence as We Build for Growth:  

    We understand that business success and development mean new challenges. Our solutions are built to scale seamlessly, accommodating increasing user bases and data volumes without sacrificing performance or security.  

5. As a company, does ASSIST have its own software products?

Yes, ASSIST Software teams have been involved in designing and developing innovative products that address community needs. One such example is the web and mobile platform Autisma. This therapy assistant enables continued learning for children diagnosed with autism spectrum disorder.   

Our extensive knowledge of the Unity and Unreal engines has allowed us to develop two mobile games, Elly and the Ruby Atlas and Hooman Invaders, as well as various Unity Assets, such as the Real-Time Weather PRO and Easy Sky. These two Unity assets allow Unity developers to control the weather and sky in their projects.   

1. Is ASSIST Software hiring right now?

We are always looking for great people to join our team, whether you're a senior software engineer or a new talent seeking an IT career. Please check our careers page and contact us. Our HR department will contact you as soon as possible.   

2. Is ASSIST Software organizing internships?

Yes. Each year, we organize individual and group internships for students. Our long-term partnership with the Stefan cel Mare University of Suceava allows us to put together great events for students and help them get started in the industry. 

3. What type of learning culture does ASSIST Software encourage?

Our focus on innovation comes from a 'can do' attitude and the continuous learning we encourage our colleagues to pursue. We frequently organize workshops, learning sessions, presentations, and masterclasses. All these events are free and open to our colleagues and aim to support their professional and personal development. 

4. How does ASSIST Software focus on teamwork?

The key to stellar teamwork is the quality time we spend together. ASSIST employees and their families are frequently invited to participate in all activities. We encourage a healthy lifestyle by promoting and organizing hikes, bike riding sessions, marathons, volleyball, football and tennis matches, ping-pong championships, and many more.   

We show our care for the environment through reforestation campaigns and forest cleaning activities.   

We also have an English-speaking club, e-sports gaming nights, tech discussions, networking parties, and board game sessions.   

5. How does ASSIST Software give back to the community?

Volunteering and charity are essential to us, which is why we founded the ASSIST Humanitarian Foundation. We genuinely care about our community and want to improve the future. We invest in IT equipment for schools and award excellent teachers. We also help hospitals and fire departments enter the 21st century.   

We sponsor cultural events and deliver humanitarian aid to those in need. If you agree with our views, you can also donate.   

ASSIST Software Team Members