The official Unity SDK for Stream Chat.
Website | Tutorial | SDK Documentation | Register for API Key
The Stream Chat SDK is the official Unity SDK for Stream Chat, a service for building chat and messaging games and applications.
- Unity Engine 6, 2023.x, 2022.x, 2021.x, 2020.x, and 2019.x Support
- IL2CPP Support
- Automatic State Management The Chat Client completely manages the state. You work with high-level models that simplify API interaction and are always up-to-date
- Automatic Reconnection Whenever the connection is lost, the chat client will reconnect automatically when the network is back
- Realtime Highly responsive experience using Websockets
- Messaging: Send direct or group messages, and have the messages persist across sessions
- Channels: group channels, private messages, etc.
- Reactions: Multiple users can react to every message, custom reactions
- Moderation: Banning (temporary, permanent, shadow), Muting (users, channels), Flagging (messages, users)
- Roles & Permissions: Admins, Moderators, custom roles with custom permission
- Moderation Dashboard Dedicated web panel to handle moderation
- Search Search through message history
- Unread counts Show the last read message per user and count unread messages
- Typing indicators See who's currently writing a new message
- Fully open-source: Complete access to the SDK source code here on GitHub
IL2CPP is supported 🚀
WebGL is supported 🚀
Stream is free for most side and hobby projects. You can use Stream Chat for free with less than five team members and no more than $10,000 in monthly revenue. Visit our website and apply for the Makers Account.
- Download the latest release .unitypackage.
- Launch Unity Editor and import the downloaded
.unitypackage - Resolve dependencies
- Start integrating Chat into your project! Check out the Tutorial to get yourself going.
Check out our tutorial on how to setup your project and perform basic operations.
In the StreamChat/SampleProject folder you'll find a fully working chat example featuring:
- Browsing channels and messages
- Sending, Editing, Deleting messaged
- Message right-click context menu
- Reactions/Emojis
- Member list with online status
- Typing indicators
- Moderation: flagging messages and users
- Sending video attachments (works only in Editor)
Created with Unity's UGUI UI system and supports both legacy and the new Unity's Input System.
- Register an account and go to Stream Dasboard
- Create App and go to its Chat Explorer throught the Dashboard
- Create new chat user and save its id
- Use our online token generator to create user token
- In Unity, provide: Api Key, User Id and User Token into
StreamChat/SampleProject/Config/DemoCredentials.asset - Open
StreamChat/SampleProject/Scenes/ChatDemo.sceneand hit play
How to enable Unity's new Input System?:
- Make sure that the UnityEngine.InputSystem package is available in the project
- Add UnityEngine.InputSystem dll reference to the StreamChat.Unity assembly definition asset
- TextMeshPro StreamChat/SampleProject requires a TextMeshPro package
- Newtonsoft.Json SDK uses Unity's package for Newtonsoft Json Library for serialization.
Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included or the current platform. Only one assembly with the same name is allowed per platform.
you can remove the StreamChat\Libs\Serialization\com.unity.nuget.newtonsoft-json@3.0.2 directory. Please note however, that Unity's package for Newtonsoft Json has IL2CPP support. If you wish to replace it and still use IL2CPP, make sure that the Json implementaion of your choice does support IL2CPP as well.
Here are some quick Code Samples to get you started. For detailed information please check out our Documentation
StreamChatClient- the main chat manager that allows you to connect with the Stream Chat Server, create channels, query channels, users, and members based on provided criteriaStreamChannel- channels group users in a conversation. Depending on your settings users may need to join channels as members in order to send messagesStreamUser- represent a single user within your applicationStreamChannelMember- object representing a user that is a member of a specific channel. This object contains propertymember.Userto access the user objectStreamMessage- represents a single message within a channel
User the StreamChatClient.CreateDefaultClient(); factory method to create an instance of IStreamChatClient:
publicclassChatManager:MonoBehaviour{publicIStreamChatClientClient{get;privateset;}protectedvoidAwake(){Client=StreamChatClient.CreateDefaultClient();}}Easiest way to start is to enable developer authorization and connect with client-side generated auth tokens:
varuserId=StreamChatClient.SanitizeUserId("user-name");varuserToken=StreamChatClient.CreateDeveloperAuthToken(userId);// Replace API_KEY with your Api Key from the Stream DashboardvarlocalUserData=awaitClient.ConnectUserAsync("API_KEY",userId,userToken);Every function that waits for response from the server you can either call using the C# modern async/await syntax or append the .AsCallback() and use as classical callbacks as follows:
Client.ConnectUserAsync("API_KEY",userId,userToken).AsCallback(onSuccess: result =>{varlocalUserData=result;},onFailure: exception =>{Debug.LogException(exception);});The .AsCallback() method accepts two delegates: Action<TResponse> onSuccess and the Action<Exception> onFailure that you can use to react to both successfull and error response case.
Instead lambda callbacks you can also provide methods with the same signature as in the example below:
publicvoidConnectUser(){varuserId=StreamChatClient.SanitizeUserId("user-name");varuserToken=StreamChatClient.CreateDeveloperAuthToken(userId);Client.ConnectUserAsync("API_KEY",userId,userToken).AsCallback(OnUserConnected,OnUserConnectionFailed);}privatevoidOnUserConnected(IStreamLocalUserDatalocalUserData){Debug.Log("User connected: "+localUserData.User.Name);}privatevoidOnUserConnectionFailed(Exceptionexception){Debug.LogException(exception);}We strongly advice using the async/await syntax which, as you'll notice in the following examples, makes the code much simpler and easier to read and maintain.
Once you're connected you can start using channels so that users can send messages.
There are 2 ways to create channels:
For predefined channels to which users can join. This is great for any general purpose channels or clans, clubs, groups which users can join or leave.
varchannel=awaitClient.GetOrCreateChannelWithIdAsync(ChannelType.Messaging,"my-channel-id");or with a callback:
Client.GetOrCreateChannelWithIdAsync(ChannelType.Messaging,"my-channel-id").AsCallback(channel =>{Debug.Log($"Channel {channel.Id} created successfully");}, exception =>{Debug.LogException(exception);});Great for public or private group messages, the order of users in group doesn't matter so whenever the users are connected using this method they will always see their chat history:
varchannel=awaitClient.GetOrCreateChannelWithMembersAsync(ChannelType.Messaging,users);To browse all channels or channels filtered by some criteria use Client.QueryChannelsAsync
varfilters=newIFieldFilterRule[]{ChannelFilter.Cid.In("channel-cid","channel-2-cid","channel-3-cid")};varsort=ChannelSort.OrderByAscending(ChannelSortFieldName.CreatedAt);varchannels=awaitClient.QueryChannelsAsync(filters,sort);The filtering mechanism is very powerful and allows you to combine multiple rules. You can check the full list of available fields and operators that you can use for channel querying here.
// Each operator usually supports multiple argument types to match your needsChannelFilter.Cid.EqualsTo("channel-cid");// stringChannelFilter.Cid.EqualsTo(channel);// IStreamChannelChannelFilter.Cid.In("channel-cid","channel-2-cid","channel-3-cid");// Comma separated stringsvarchannelCids=newList<string>{"channel-1-cid","channel-2-cid"};ChannelFilter.Cid.In(channelCids);// Any collection of stringvarfilters=newIFieldFilterRule[]{ChannelFilter.CreatedById.EqualsTo(Client.LocalUserData.User)};varfilters=newIFieldFilterRule[]{ChannelFilter.MembersCount.GreaterThan(10)};varweekAgo=DateTime.Now.AddDays(-7).Date;varfilters=newIFieldFilterRule[]{ChannelFilter.CreatedAt.GreaterThan(weekAgo)};vardayAgo=DateTime.Now.AddHours(-24);varfilters=newIFieldFilterRule[]{ChannelFilter.UpdatedAt.GreaterThan(dayAgo)};Messages are accessible via channel.Messages property that contains collection of the most recent messages. Because there can potentialy be thousands of messages in a channel history the channel.Messages collection contains only the latest messages. You can load older messages by calling the channel.LoadOlderMessagesAsync() which will load additional portion of the history. A common approach is to call channel.LoadOlderMessagesAsync() whenever users hits the end of your messages scroll view, this way you only load older messages when the user actually wants to view them. You can see an example of this approach in Sample Project's MessageListView.cs
varsentMessage=awaitchannel.SendNewMessageAsync("Hello");varmessageInThread=awaitchannel.SendNewMessageAsync(newStreamSendMessageRequest{ParentId=parentMessage.Id,// Write in threadShowInChannel=false,// Optionally send to both thread and the main channel like in SlackText="Hello",});varmessageWithQuote=awaitchannel.SendNewMessageAsync(newStreamSendMessageRequest{QuotedMessage=quotedMessage,// Reference to IStreamMessage Text="Hello",});Silent messages do not trigger events for channel members. Often used for system messages
varsilentMessage=awaitchannel.SendNewMessageAsync(newStreamSendMessageRequest{Text="System message",Silent=true});awaitmessage.PinAsync();awaitmessage.PinAsync(newDateTime().AddDays(7));// Pin for 7 daysawaitmessage.UnpinAsync();awaitmessage.UpdateAsync(newStreamUpdateMessageRequest{Text="New changed message",});awaitmessage.UpdateAsync(newStreamUpdateMessageRequest{CustomData=newStreamCustomDataRequest{{"CategoryId",12},{"Awards",newstring[]{"Funny","Inspirational"}}}});Only clears the text but leaves other related data, reactions, thread sub-messages, etc. intact
awaitmessage.SoftDeleteAsync();Removes a message completely and removes all data related to this message
awaitmessageInChannel.HardDeleteAsync();awaitmessage.SendReactionAsync("like");awaitmessage.SendReactionAsync("clap",10);awaitmessage.SendReactionAsync("love",enforceUnique:true);awaitmessage.DeleteReactionAsync("like");// Get file byte array however you want e.g. Addressables.LoadAsset, Resources.Load, etc.varsampleFile=File.ReadAllBytes("path/to/file");varfileUploadResponse=awaitchannel.UploadFileAsync(sampleFile,"my-file-name");varfileWebUrl=fileUploadResponse.FileUrl;varsampleImage=File.ReadAllBytes("path/to/file");varimageUploadResponse=awaitchannel.UploadImageAsync(sampleFile,"my-image-name");varimageWebUrl=imageUploadResponse.FileUrl;varchannel=awaitClient.GetOrCreateChannelWithIdAsync(ChannelType.Messaging,channelId:"my-channel-id");awaitchannel.DeleteFileOrImageAsync("file-url");Channel objects are being automatically updated whenever any change occur (new messages, reactions, etc.). You can react to these changes by subscribing to IStreamChannel exposed events:
channel.MessageReceived+=OnMessageReceived;channel.MessageUpdated+=OnMessageUpdated;channel.MessageDeleted+=OnMessageDeleted;channel.ReactionAdded+=OnReactionAdded;channel.ReactionUpdated+=OnReactionUpdated;channel.ReactionRemoved+=OnReactionRemoved;varlocalUserData=Client.LocalUserData;varlocalUser=localUserData.User;- Local User Data - Additional data related to the user connected on the local device like: muted channels, list of devices, unread channels, unread messages, etc.
- Local User - instance of
StreamUserrepresenting the user on the local device
varusers=awaitClient.QueryUsersAsync();varusers=awaitClient.QueryUsersAsync(newDictionary<string,object>(){{"id",newDictionary<string,object>{{"$eq",otherUserId}}}});varotherUser=users.First();varfilters=newDictionary<string,object>{{"id",newDictionary<string,object>{{"$in",listOfUserIds}}}};varusers=awaitClient.QueryUsersAsync(filters);Read more on supported query parameters and operators
Depending on your app configuration users may need to join channels as members in order to send messages or see other users messages
// Multiple overloads available depending on your needsawaitchannel.AddMembersAsync(user);// instance of IStreamUserawaitchannel.AddMembersAsync(user1,user1);// Multiple instances of IStreamUserawaitchannel.AddMembersAsync(listOfUsers);// List<IStreamUser>awaitchannel.AddMembersAsync("user-id");// string IDawaitchannel.AddMembersAsync(listOfUserIds);// List<string> that contains IDs// Multiple overloads available depending on your needsawaitchannel.RemoveMembersAsync(member);// instance of IStreamChannelMemberawaitchannel.RemoveMembersAsync(member1,member2);// Multiple instances of IStreamChannelMemberawaitchannel.RemoveMembersAsync(listOfMembers);// List<IStreamChannelMember>awaitchannel.RemoveMembersAsync(user);// instance of IStreamUserawaitchannel.RemoveMembersAsync(user1,user1);// Multiple instances of IStreamUserawaitchannel.RemoveMembersAsync(listOfUsers);// List<IStreamUser>awaitchannel.RemoveMembersAsync("user-id");// string IDawaitchannel.RemoveMembersAsync(listOfUserIds);// List<string> that contains IDsStream provides all the necessary tools and features to properly manage a large community.
Flagging means that this user or message will be reported to the chat moderation. Chat admins and moderators can view reported users and messages in the Dashboard.
awaituser.FlagAsync();awaitmessage.FlagAsync();awaitchannel.BanUserAsync(user);awaitchannel.BanUserAsync(user,"You got banned for 2 hours for toxic behaviour.",120);Banning IP helps to prevent case where user creates a new account to bypass the ban.
awaitchannel.BanUserAsync(user,timeoutMinutes:120,isIpBan:true);awaitchannel.BanUserAsync(user,"You got banned for 2 hours for toxic behaviour.",120);varrequest=newStreamQueryBannedUsersRequest{CreatedAtAfterOrEqual=newDateTimeOffset().AddHours(-24),Limit=30,Offset=0,};varbannedUsersInfo=awaitClient.QueryBannedUsersAsync(request);Shadow banned user doesn't know he's being banned. This is sometimes helpful because it takes additional time for a user to realize the he's banned.
awaitchannel.ShadowBanUserAsync(user);awaitchannel.ShadowBanMemberAsync(channelMember);awaituser.MuteAsync();awaituser.UnmuteAsync();awaitchannel.MuteChannelAsync();awaitchannel.UnmuteChannelAsync();The above examples are only a few out of many - check out our Full Documentation for more insight and examples
Go ahead and open GitHub Issue with your request and we'll respond as soon as possible.
Reach out to our Support.
We've recently closed a $38 million Series B funding round and we keep actively growing. Our APIs are used by more than a billion end-users, and you'll have a chance to make a huge impact on the product within a team of the strongest engineers all over the world. Check out our current openings and apply via Stream's website.

