Skip to main content

Overview

This guide will walk you through integrating the Discord Social SDK into a Unity project. By the end, you’ll have a project that can:
  • Authenticate users with Discord
  • Set up logging and status monitoring
  • Start the SDK and establish a connection
  • Request the number of Discord friends the player has
  • Set the player’s rich presence for your game

Prerequisites

Before starting, ensure you have:

Step 1: Create your Discord application

  1. Go to the Discord Developer Portal and click New Application.
  2. Give your application a name and click Create.
  3. Copy your Application ID — you’ll need it in the Unity inspector.

Step 2: Configure OAuth2 redirect URIs

  1. In your application settings, click OAuth2 in the sidebar.
  2. Under Redirects, add http://127.0.0.1/callback.
  3. Click Save Changes.

Step 3: Enable public client (optional)

If your application does not have a backend server, enable Public Client in the OAuth2 settings.

Step 4: Download the Social SDK for Unity

  1. In your application settings, click Downloads under the Discord Social SDK section in the sidebar.
  2. Select the latest version from the dropdown and download the SDK for Unity.
A Unity sample project is also available on the downloads page. Explore it after completing this guide.

Step 5: Project setup

  1. Create a new 2D project in Unity Hub using Unity 2021.3 or later.
  2. Either unzip the SDK archive into the Unity Packages folder, or unzip it and install the package from disk.
  3. In your project, add a Scripts folder and create a DiscordManager.cs script.
  4. Add the following initial code to DiscordManager.cs:
using UnityEngine;
using UnityEngine.UI;
using Discord.Sdk;
using System.Linq;

public class DiscordManager : MonoBehaviour
{
    [SerializeField]
    private ulong clientId; // Set this in the Unity Inspector

    [SerializeField]
    private Button loginButton;

    [SerializeField]
    private Text statusText;

    private Client client;
    private string codeVerifier;
}
  1. Add an empty GameObject to the scene (GameObject > Create Empty) called DiscordManager and attach the script.
  2. Add a button (GameObject > UI > Legacy > Button) and text (GameObject > UI > Legacy > Text) to the scene.
  3. Attach the button and text to the DiscordManager in the inspector.
  4. Enter your Application ID in the Client Id field in the inspector.

Step 6: Set up SDK event handling

Add callbacks to monitor your Discord connection. Update DiscordManager.cs:
void Start()
{
    client = new Client();

    client.AddLogCallback(OnLog, LoggingSeverity.Error);
    client.SetStatusChangedCallback(OnStatusChanged);

    if (loginButton != null)
    {
        // loginButton.onClick.AddListener(StartOAuthFlow);
    }

    if (statusText != null)
    {
        statusText.text = "Ready to login";
    }
}

private void OnLog(string message, LoggingSeverity severity)
{
    Debug.Log($"Log: {severity} - {message}");
}

private void OnStatusChanged(Client.Status status, Client.Error error, int errorCode)
{
    Debug.Log($"Status changed: {status}");
    statusText.text = status.ToString();
    if (error != Client.Error.None)
    {
        Debug.LogError($"Error: {error}, code: {errorCode}");
    }
}
The Unity plugin handles running SDK callbacks automatically — no need to call RunCallbacks() manually like in the C++ guide.

Step 7: Account linking with Discord

Implement OAuth2 authentication to connect users with their Discord accounts.
This guide uses Client.GetDefaultPresenceScopes(), which requests the openid and sdk.social_layer_presence scopes. These enable core features like account linking, friends list, and rich presence.If your game also needs lobbies, voice chat, or direct messaging, use Client.GetDefaultCommunicationScopes() instead. See the OAuth2 scopes guide for details.
Add the OAuth flow methods to DiscordManager.cs:
private void StartOAuthFlow()
{
    var authorizationVerifier = client.CreateAuthorizationCodeVerifier();
    codeVerifier = authorizationVerifier.Verifier();

    var args = new AuthorizationArgs();
    args.SetClientId(clientId);
    args.SetScopes(Client.GetDefaultPresenceScopes());
    args.SetCodeChallenge(authorizationVerifier.Challenge());
    client.Authorize(args, OnAuthorizeResult);
}

private void OnAuthorizeResult(ClientResult result, string code, string redirectUri)
{
    Debug.Log($"Authorization result: [{result.Error()}] [{code}] [{redirectUri}]");
    if (!result.Successful())
    {
        return;
    }
    GetTokenFromCode(code, redirectUri);
}

private void GetTokenFromCode(string code, string redirectUri)
{
    client.GetToken(clientId, code, codeVerifier, redirectUri,
        (result, token, refreshToken, tokenType, expiresIn, scope) => {});
}
Then uncomment the button listener in Start():
loginButton.onClick.AddListener(StartOAuthFlow);
Never log or store access tokens insecurely. Treat them as sensitive credentials.

Step 8: Connect the SDK to Discord

Add the token handling methods and update GetTokenFromCode to call them:
private void OnReceivedToken(string token)
{
    Debug.Log("Token received: " + token);
    client.UpdateToken(AuthorizationTokenType.Bearer, token,
        (ClientResult result) => { client.Connect(); });
}

private void OnRetrieveTokenFailed()
{
    statusText.text = "Failed to retrieve token";
}
Update GetTokenFromCode:
private void GetTokenFromCode(string code, string redirectUri)
{
    client.GetToken(clientId, code, codeVerifier, redirectUri,
        (result, token, refreshToken, tokenType, expiresIn, scope) => {
            if (token != "")
            {
                OnReceivedToken(token);
            }
            else
            {
                OnRetrieveTokenFailed();
            }
        });
}
Press play and click the button. You should see the status text change through the OAuth flow and end up as Ready.

Step 9: Access Discord relationships

Add a method to display friend count when the client is ready:
private void ClientReady()
{
    Debug.Log($"Friend Count: {client.GetRelationships().Count()}");
}
Update OnStatusChanged to call it:
private void OnStatusChanged(Client.Status status, Client.Error error, int errorCode)
{
    Debug.Log($"Status changed: {status}");
    statusText.text = status.ToString();
    if (error != Client.Error.None)
    {
        Debug.LogError($"Error: {error}, code: {errorCode}");
    }

    if (status == Client.Status.Ready)
    {
        ClientReady();
    }
}
Example console output after login:
Friend Count: 42

Step 10: Set rich presence

Update ClientReady to also set rich presence:
private void ClientReady()
{
    Debug.Log($"Friend Count: {client.GetRelationships().Count()}");

    Activity activity = new Activity();
    activity.SetType(ActivityTypes.Playing);
    activity.SetState("In Competitive Match");
    activity.SetDetails("Rank: Diamond II");

    client.UpdateRichPresence(activity, (ClientResult result) => {
        if (result.Successful())
        {
            Debug.Log("Rich presence updated!");
        }
        else
        {
            Debug.LogError("Failed to update rich presence");
        }
    });
}

Conclusion

You’ve successfully integrated the Discord Social SDK into Unity.

What you’ve built

  • A Discord application configured with OAuth2
  • SDK logging and status monitoring
  • User authentication flow
  • Discord relationships data retrieval
  • Rich Presence support

Next steps

Check out the Unity sample project on GitHub for drop-in prefabs with both code and UI to quickly integrate Discord’s social features into your game.

Creating a unified friends list

Build a unified friends list combining Discord and game-specific friendships.

Setting rich presence

Customize your game’s rich presence to show advanced information and game invites.

Managing lobbies

Bring players together in a shared lobby with text chat and voice communication.

Change log

DateChanges
March 17, 2025Initial release