Go Back

UnityHooks

A wrapper written in C# for the Discord Webhook API. Includes most functionalities to send webhooks from Unity over to Discord.

by Shahin Mohseni, Dec 12, 2024 (updated: Dec 13, 2024)
C#Unity

Introduction

UnityHooks is my solution to easily send data from Unity over to Discord. This could be player highscores, or data about the server status or load. This wrapper includes features to add embeds, thumbnails, images, footers and links. To fit each developers, the wrapper includes both method chaining and a way to directly set properties.

Showcase

The video below shows UnityHooks in action with UI elements hooked up to show the response of the webhook being sent.

As mentioned above, the wrapper includes 2 ways of creating webhooks, with the first being method chaining.

Method chaining

By returning the instance after each method call you can chain methods to each other when creating webhooks.

Uri webhook_url = new("your webhook url here");
Webhook hook = new(webhook_url);
Embed embed = new Embed()
    .SetTitle("Title")
    .SetColor(Colors.Yellow)
    .AddField("this is a field title", "this is a field value");

hook.AddEmbed(embed);

var (result, responseCode, error) = await hook.Send();
string log_message = $"Result: {result}, Response code: {responseCode}, Error: {error}";

Debug.Log(hook.ToJson());
Debug.Log(log_message);

Editing properties

If the method chaining approach isn’t to the developers liking, I also provide a way to edit the webhook as an object by providing the necessary properties.

Uri URL = new("this is the url for images");
Uri webhook_url = new("your webhook url here");

Webhook hook = new(webhook_url);
hook.AddEmbed(new()
{
    title = "Title (with url)",
    thumbnail = new()
    {
        url = URL
    },
    description = "description",
    url = new("https://www.github.com"),
    color = Colors.Orange,
    timestamp = DateTime.UtcNow.ToString(),
    fields = new List<Embed.Field>() {
    new Embed.Field() {
        name = "field 1",
        value = "field 1",
        inline = true
    },
});

var (result, responseCode, error) = await hook.Send();
string log_message = $"Result: {result}, Response code: {responseCode}, Error: {error}";
text_field.text = log_message;

Debug.Log(hook.ToJson());
Debug.Log(log_message);

Creating a webhook

To send webhooks you are required to have a URL that includes the channel id as well as the webhook token. To obtain this URL you can follow Discord’s guide to create a webhook in Discord. Once the webhook is created, you can copy the webhook URL as this will be used for authentication.