How to Create a Twitch Chat Game with Unity

Learn to integrate the Twitch Chat API into your Unity game, so viewers can interact with the game during streaming. By Harrison Hutcheon.

4.7 (3) · 3 Reviews

Download materials
Save for later
Share

Twitch is a streaming platform where content creators broadcast themselves live. While broadcasting, viewers interact with each other and the streamer through simple text chat.

Users chatting with a streamer

Some content creators realized they could use chat messages to control a game. The most famous example of this is Twitch Plays Pokemon, where viewers control a modified version of Pokémon Red through simple commands.

A clip of popular stream game, Twitch Plays Pokemon

Stream games are a great way to build and maintain a dedicated audience. They create a sense of community, friendly competition and engage viewers in new and exciting ways. Viewers love to feel like they can directly interact with their favorite content creators, and stream games are a great way to provide that experience.

In this tutorial, you’ll learn:

  • How to read messages from Twitch chat into Unity.
  • Validate commands that can interact with your game.
  • All about the different types of audience interaction you could implement.
  • Create your very own Pokémon-like Battle game can be played by the audience.
Note: This tutorial uses Unity version 2020.3. If you don’t have this version of Unity installed, you can use Unity Hub to install and manage multiple Unity versions across your projects. You’ll also need a Twitch account.

Getting Started

Click Download Materials at the top or bottom of this tutorial to download the starter and final projects. Extract them. Then open Twitch Chat Game Starter using the Unity Editor.

Take a look at Assets/RW. Here you’ll see your project folders, including:

  • Prefabs
  • Scenes
  • Scripts
  • Sprites

RW/Scenes contains two scene files: Battle and Golf.

For this tutorial, you’ll work in Battle. You can use Golf for a bonus game at the end of the article.

The first step in creating a Twitch Chat game is connecting your app to your Twitch account and parsing incoming messages.

The Twitch Chat Script

If you haven’t already, open the Battle scene. In Assets/RW/Scripts/Common create a script called TwitchChat.

Import the System.IO and System.Net.Sockets namespaces:

using System.IO;
using System.Net.Sockets;

In TwitchChat‘s body, create the fields shown below:

public string username; // 1
public string password; 
public string channelName; 

private TcpClient twitchClient; // 2
private StreamReader reader; // 3
private StreamWriter writer; 
private float reconnectTimer; // 4 
private float reconnectAfter; 

Here’s a code breakdown:

  1. These strings hold your twitch account credentials, letting your app connect to your account.
  2. You declare a private TcpClient, which establishes a connection with Twitch using your credentials.
  3. Then you create a private StreamReader and private StreamWriter. The StreamWriter sends your credentials to Twitch and the StreamReader pulls in the messages from chat.
  4. reconnectTimer tracks the amount of time passed since connecting while reconnectAfter sets how long to wait before attempting to reconnect. Sometimes the connection to Twitch closes automatically, so the app should attempt to reconnect after a short time.

Create a private method called Connect. Implement it as below:

private void Connect()
{
    twitchClient = new TcpClient("irc.chat.twitch.tv", 6667); // 1
    reader = new StreamReader(twitchClient.GetStream()); // 2
    writer = new StreamWriter(twitchClient.GetStream()); 
    writer.WriteLine("PASS " + password); // 3
    writer.WriteLine("NICK " + username); 
    writer.WriteLine("USER " + username + " 8 *:" + username); 
    writer.WriteLine("JOIN #" + channelName); 
    writer.Flush(); 
}

This method:

  1. Instantiates twitchClient with the URL for the Twitch chat API and the port.
  2. Then instantiates both reader and writer with twitchClient.GetStream().
  3. Uses writer to pass your credentials to Twitch.

Add the following to Start:

reconnectAfter = 60.0f;
Connect();   

This code sets reconnectAfter to 60 seconds and calls Connect.

Now TwitchChat is ready to start reading in chat messages from Twitch.

Reading in Chat Messsages From Twitch

Add the following ReadChat method:

public void ReadChat()
{
    if (twitchClient.Available > 0) // 1
    {
        string message = reader.ReadLine();

        if (message.Contains("PRIVMSG")) // 2
        {
            print(message); 
        }
    }
}

Here’s a code breakdown:

  1. In ReadChat, you check if twitchClient.Available is greater than 0. If so, you save reader.ReadLine() to message.
  2. If message contains “PRIVMSG”, it’s a user created message. Print the message to the Unity console.

Then inside Update, add:

if (twitchClient.Available == 0) // 1
{
    reconnectTimer += Time.deltaTime; 
}

if (twitchClient.Available == 0 && reconnectTimer >= reconnectAfter) // 2
{
    Connect(); 
    reconnectTimer = 0.0f; 
}

ReadChat(); // 3

Here, you:

  1. Check if twitchClient.Available is 0. If it is 0, you add Time.deltaTime to reconnectTimer.
  2. If reconnectTimer is greater than or equal to reconnectAfter, the app disconnected for a minute. In that case, reconnect with Connect, and reset reconnectTimer to 0.
  3. Then, call ReadChat() to read in the messages.

Later, TwitchChat will filter commands from regular messages. For now, you’ll test to make sure it works.

In the Hierarchy, add TwitchChat to GameManager, found in Managers. Fill in the TwitchChat fields with your Twitch credentials.

The username and channel name fields should both be your Twitch username. Head over to twitchapps.com/tmi to generate a API token. Copy this into the password field.

Shows how the Twitch Chat script should look in the Unity Inspector.

With your credentials filled out, you’re ready to test!

Press Play and open your Twitch channel in a web browser. Try typing some messages into the chat. Even when not broadcasting, you’ll see them appear in Unity’s console.

Stream chat appearing in the unity console

Parsing Chat Commands

You want to be able to differentiate between then messages sent to your app and the user that sent them.

In RW/Scripts/Common, create a script called ChatMessage. Note it is not a Monobehaviour and simply holds two variables:

[System.Serializable]
public class ChatMessage
{
    public string user;
    public string message;
}

ChatMessage holds a message and the username of the user that sent it. It also uses System.Serializable to store it in a List.

In TwitchChat, update ReadChat to:

public ChatMessage ReadChat() // 1
{
    if (twitchClient.Available > 0)
    {
        string message = reader.ReadLine();

        if (message.Contains("PRIVMSG"))
        {
            // Get the username
            int splitPoint = message.IndexOf("!", 1); // 2
            string chatName = message.Substring(0, splitPoint); 
            chatName = chatName.Substring(1);

            //Get the message
            splitPoint = message.IndexOf(":", 1); 
            message = message.Substring(splitPoint + 1);
            ChatMessage chatMessage = new ChatMessage(); // 3
            chatMessage.user = chatName;
            chatMessage.message = message.ToLower();
            return chatMessage;
        }

    }
    return null; // 4
}

This updated code:

  1. Returns a ChatMessage and removes the print call.
  2. Splits the message to get the body of the message and the username of the user who sent it.
  3. Stores these values in a new ChatMessage and returns it.
  4. Since ReadChat now needs to return something, it returns null at the bottom of the method, when no connection was available.

Now you need to process messages to find game commands, validate them, then execute them.