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.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
How to Create a Twitch Chat Game with Unity
45 mins
- Getting Started
- The Twitch Chat Script
- Reading in Chat Messsages From Twitch
- Parsing Chat Commands
- Parsing and Storing Commands
- The Game Manager
- Validating Commands
- Testing Commands
- Your Twitch Audience and You
- Audience vs Audience
- Audience vs Game
- Audience vs Streamer
- Common Design Challenges
- Delay
- Audience Interaction
- Streamer Interaction
- Where's the Fun?
- Exploring the Sample Scene
- Creating Commands
- Expanding the Vote Script
- Game Over and New Game Conditions
- Game Over Check
- Game Over Action
- New Game Action
- Revisiting the GameManager
- Using What You've Learned
- Where to Go From Here?
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.
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.
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.
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:
- These strings hold your twitch account credentials, letting your app connect to your account.
- You declare a private
TcpClient
, which establishes a connection with Twitch using your credentials. - Then you create a private
StreamReader
and privateStreamWriter
. TheStreamWriter
sends your credentials to Twitch and theStreamReader
pulls in the messages from chat. -
reconnectTimer
tracks the amount of time passed since connecting whilereconnectAfter
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:
- Instantiates
twitchClient
with the URL for the Twitch chat API and the port. - Then instantiates both
reader
andwriter
withtwitchClient.GetStream()
. - 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:
- In
ReadChat
, you check iftwitchClient.Available
is greater than 0. If so, you savereader.ReadLine()
tomessage
. - 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:
- Check if
twitchClient.Available
is 0. If it is 0, you addTime.deltaTime
toreconnectTimer
. - If
reconnectTimer
is greater than or equal toreconnectAfter
, the app disconnected for a minute. In that case, reconnect withConnect
, and resetreconnectTimer
to 0. - 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.
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.
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:
- Returns a
ChatMessage
and removes theprint
call. - Splits the message to get the body of the message and the username of the user who sent it.
- Stores these values in a new
ChatMessage
and returns it. - Since
ReadChat
now needs to return something, it returnsnull
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.