Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to integrate Discord with a Unity Game

Nowadays, a huge majority of gamers use Discord on the site while playing or doing any other activity. The platform has become a very popular choice for communicating with other players, friends, streaming what you’re doing, sharing screenshots, etc and as such, a huge majority of games have added integrations to work alongside discord. In this tutorial, we will cover how to display some text and an icon on the user’s profile using the discord SDK, but know that it is also possible to do more with it, such as adding the possibility for people to join your party in-game through your profile and more. I may explain more in future tutorials.

Getting setup

To get started, you’ll need two things:

  1. Download the latest stable version of the discord sdk here. As of writing there are two versions, v2.5.6 and v3.2.1, but despite there not being exactly a “LTS” and a “Latest” version, I’d recommend getting the first, as its been tested more and is the one that works best for me. If it throws any errors on your project, then I’d recommend trying the most recent one
  2. Go to the developer website and make an account. Your developer account and your discord account basically the same, so if you already use discord you can just log-in using that.

With both of those things done, open your project in Unity, open the zip file you downloaded on step one and extract its contents somewhere on your desktop. After that, grab the folderslib” and “csharp” and place them somewhere inside your unity project(I recommend creating a specific folder for them).

After that, you’ll need to make a new application in the developer portal. To do so, simply click “New Application” on the top right corner, give it a name and check the “I agree with the terms of service” checkbox. You’ll then be redirected to a page like the following:

It isn’t necessary to give your application a description or even tags, however if you scroll down you’ll see an important field called “Application ID“.

Within discord’s docs page, they say to use “CLIENT_id” to connect to your application but the actual name within the dev portal is Application ID. Keep note of that number for the next part of the tutorial.

Next, head to “Rich Presence” > “Art Assets“. There you can upload images in different resolutions and give them names in other to use later, within your code, for Icons for different parts of your game. You can also upload a cover image for the game that will show on invites, but we won’t be covering those here.

Starting to code

For those who don’t like coding, before we try and make anything custom, know that you can go to Rich Presence > Visualizer, customize a few of the fields there and then click “Show code” and you should get at least a part of the necessary code, that you can just throw in unity.

Now, to create a basic custom status display, first make a “DiscordPluginC# Script. Within it, create two variables “public Discord.Discord discord” and “private Discord.Activity activity“(I’ll display the full code at the end). Those will represent the discord object and the activity object(the status). Don’t forget to create a variable to help count the passage of time, like for example “public long beginningoftime” and a waitforseconds variable we will use later “public WaitForSeconds halfsec=new WaitForSeconds(0.5f);“. It will also necessary to addusing Discord;” to the very beginning of the code to make it work.

Moving to the Start function, add the following code:

beginningoftime=System.DateTimeOffset.Now.ToUnixTimeMilliseconds(); 
discord = new Discord.Discord(YourApplicationID, (UInt64)Discord.CreateFlags.NoRequireDiscord); 
discord.SetLogHook(Discord.LogLevel.Debug, (level, message) =>
{
  Debug.Log("Log "+ level+ message);
});

This will set the variable beginningoftime in milliseconds passed since 1970-01-01T00:00:00.000Z, creates a discord object(remember to replace “YourApplicationID” with your application ID from the steps above), and set a log hook. The second argument on the second line “Discord.CreateFlags.NoRequireDiscordserves to not make discord a requirement for the game to run(using “Discord.CreateFlags.Default” will crash your application and force open discord if its not already open).

Before we continue with the start Function, let’s declare a new function calledUpdateActivity“, of the type void since it doesn’t need to return anything. It should look like this:

void UpdateActivity(Discord.Discord discord)
{    
        
        
        activity = new Discord.Activity
        {
            State="Text to Display",
            Timestamps =
            {
                Start = beginningoftime,
                
            },
            Assets =
            {
                LargeImage = "ALargeIcon",
                SmallImage = "ASmallIcon",
            },
        };
        
        discord.GetActivityManager().UpdateActivity(activity, result =>{});
}

This function will be constantly called to update the content being displayed on the player’s profile. As you can see, it contains a field called “State” that represents the text to be displayed, “Timestamps” (usually containing Start and End, but since we want to count up, don’t add an End one) to count the passage of time, and “Assets“, which I included Large and Small Image names, set previously in the Developer portal > Rich Presence > Art Assets.

Now back to the start function, add the following below what you already have:

UpdateActivity(discord);
discord.RunCallbacks();

StartCoroutine(Updater());

This will call the function we created previously, setting an activity, run the callbacks(which will basically send to discord all the changes) and as you may notice, call a coroutine we have yet to make called “Updater“. Let’s creat it:

IEnumerator Updater(){
    yield return halfsec;

    discord.RunCallbacks();
    beginningoftime=System.DateTimeOffset.Now.ToUnixTimeMilliseconds(); 
    
    UpdateActivity(discord);
    StartCoroutine(Updater());
}

This coroutine will wait for half a second, run all the callbacks, update the variable marking the passage of time, prepare the next activity update then call itself again. The reason I prefer this over running a similar code but within an Update() function is due to performance. Running this once every frame(which usually means 60 times a second) can impact performance on weaker systems, so in this tutorial we only do it two times a second.

Finally, your DiscordPlugin.cs should look like this:

using Discord; 
using System;

public class DiscordPlugin : MonoBehaviour
{

public Discord.Discord discord;
private Discord.Activity activity;
public long beginningoftime;
public WaitForSeconds halfsec=new WaitForSeconds(0.5f);

void Start()
{
    beginningoftime=System.DateTimeOffset.Now.ToUnixTimeMilliseconds();
    discord = new Discord.Discord(YourApplicationID, (UInt64)Discord.CreateFlags.NoRequireDiscord);
    discord.SetLogHook(Discord.LogLevel.Debug, (level, message) =>
    {
        Debug.Log("Log "+ level+ message);
    });
    
    UpdateActivity(discord);
    discord.RunCallbacks();

    StartCoroutine(Updater());
}

void UpdateActivity(Discord.Discord discord)
{    
        
        
        activity = new Discord.Activity
        {
            State="Text to Display",
            Timestamps =
            {
                Start = beginningoftime,
                
            },
            Assets =
            {
                LargeImage = "ALargeIcon",
                SmallImage = "ASmallIcon",
            },
        };
        
        discord.GetActivityManager().UpdateActivity(activity, result =>{});
}

IEnumerator Updater(){
    yield return halfsec;

    discord.RunCallbacks();
    beginningoftime=System.DateTimeOffset.Now.ToUnixTimeMilliseconds(); 
    
    UpdateActivity(discord);
    StartCoroutine(Updater());
}

}

Save it, and drag it into an object that will always be present in your game(something like a GameManager). If you haven’t setup one yet, just add “DontDestroyOnLoad(this.gameObject);” to the Start function, create an object on the main scene and call it GameManager then place the whole script there. That way it won’t be destroyed upon scene load like objects normally are. Save the project and run the game, and you will see your discord status change!



This post first appeared on Peq42 - Indie Game Dev, please read the originial post: here

Share the post

How to integrate Discord with a Unity Game

×

Subscribe to Peq42 - Indie Game Dev

Get updates delivered right to your inbox!

Thank you for your subscription

×