The creator-centric platform for building live games in Unity

Easily add social, commerce, and content management features to your live game with low-code, drag-and-drop prefabs fully integrated with your Unity workflow.

Chat

Allow players to communicate in-game

Overview

This page includes everything needed to use this feature in the "Beamable SDK for Unity".

The purpose of this feature is to allow players to communicate together in-game with text chat.

With chat, the players collaborate and discuss strategies during cooperation and trade messages during competition.

In-game chat can help your game keep its players, give them opportunities to socialize, and increase their Lifetime Value. - Medium.com

šŸ“˜

Use Cases

This functionality has various use cases for game makers and players.

ā€¢ Single Player Games - Broaden the metagame with social features to boost retention
ā€¢ Multiplayer Games - Deepen the core game to increase engagement. See Multiplayer for more info

Players can easily send and receive messages in real-time.

Send Room Message

room.SendMessage("Hello World!");

Receive Room Message

private void OnMessageReceived (Message message)
{
  Debug.Log($"Message = {message.content}");
}

Glossary

Here is the glossary of chat-related terms.

Name

Detail

Room

A collection of game players (e.g. chatting about a specific topic)

Room Player

A game player within the room

Message

Text sent from one player to all players within the room

API

Unlike many Beamable FeatureFeature - An individual aspect of the Beamable product used to create a great user experiences, Chat does not require a specific Beamable Feature PrefabFeature Prefab - The drag-and-drop template for a specific Beamable product feature to be used. The main entry point to this feature is C# programming.

šŸ“˜

Learning Fundamentals

Game makers who are new to Unity and C# can review the fundamentals here.

ā€¢ See Beamable: Asynchronous Programming for more info

Here are API highlights for beamableAPI.ChatService.

Method Name

Detail

Subscribe

Callback to observe changes

CreateRoom

Create a new room

GetMyRooms

Get list of all current rooms

LeaveRoom

Leave the current room

SendMessage

Send a text message to all room players

Examples

Here are examples which cover common programming needs.

šŸ“˜

Beamable SDK Examples

ā€¢ This and all examples are available for download at GitHub.com/Beamable_SDK_Examples

In this example, the player may create a room and send a chat message.

using System.Collections.Generic;
using System.Threading.Tasks;
using Beamable.Common.Api;
using UnityEngine;
using Beamable.Experimental.Api.Chat;
using UnityEngine.Events;

namespace Beamable.Examples.Labs.ChatService
{
    /// <summary>
    /// Holds data for use in the <see cref="ChatServiceExampleUI"/>.
    /// </summary>
    [System.Serializable]
    public class ChatServiceExampleData
    {
        public List<string> RoomNames = new List<string>();
        public List<string> RoomPlayers = new List<string>();
        public List<string> RoomMessages = new List<string>();
        public string RoomToCreateName = "";
        public string RoomToLeaveName = "";
        public bool IsInRoom = false;
        public string MessageToSend = "";
    }
   
    [System.Serializable]
    public class RefreshedUnityEvent : UnityEvent<ChatServiceExampleData> { }
    
    /// <summary>
    /// Demonstrates <see cref="ChatService"/>.
    /// </summary>
    public class ChatServiceExample : MonoBehaviour
    {
        //  Events  ---------------------------------------
        [HideInInspector]
        public RefreshedUnityEvent OnRefreshed = new RefreshedUnityEvent();
        
        //  Fields  ---------------------------------------
        private ChatView _chatView = null;
        private IBeamableAPI _beamableAPI = null;
        private ChatServiceExampleData _data = new ChatServiceExampleData();
    
        //  Unity Methods  --------------------------------
        protected void Start()
        {
            Debug.Log("Start()");

            SetupBeamable();
        }
        
        //  Methods  --------------------------------------
        private async void SetupBeamable()
        {
            _beamableAPI = await Beamable.API.Instance;

            Debug.Log($"beamableAPI.User.id = {_beamableAPI.User.id}");

            // Observe ChatService Changes
            _beamableAPI.Experimental.ChatService.Subscribe(chatView =>
            {
                _chatView = chatView;
                
                // Clear data when ChatService changes
                _data.RoomNames.Clear();
                _data.RoomMessages.Clear();
                _data.RoomPlayers.Clear();
                
                foreach(RoomHandle room in chatView.roomHandles)
                {
                    room.OnRemoved += Room_OnRemoved;
                    
                    string roomName = $"{room.Name}";
                    _data.RoomNames.Add(roomName);
                    
                    room.Subscribe().Then(_ =>
                    {
                        // Clear data (again) when Room changes
                        _data.RoomMessages.Clear();
                        _data.RoomPlayers.Clear();
                        _data.RoomToLeaveName = room.Name;
                        
                        foreach(var message in room.Messages)
                        {
                            string roomMessage = $"{message.gamerTag}: {message.content}";
                            _data.RoomMessages.Add(roomMessage);
                        }
                        
                        
                        foreach(var player in room.Players)
                        {
                            string playerName = $"{player}";
                            _data.RoomPlayers.Add(playerName);
                        }
                        
                        Refresh();
                    });
                    room.OnMessageReceived += Room_OnMessageReceived;
                }
                Refresh();
            });
        }



        public async Task<bool> IsProfanity(string text)
        {
            bool isProfanityText = true;
            try
            {
                var result = await _beamableAPI.Experimental.ChatService.ProfanityAssert(text);
                isProfanityText = false;
            } catch{}

            return isProfanityText;
        }
        
        public async Task<EmptyResponse> SendRoomMessage()
        {
            string messageToSend = _data.MessageToSend;
            
            bool isProfanity  = await IsProfanity(messageToSend);

            if (isProfanity)
            {
                // Disallow (or prompt Player to resubmit)
                messageToSend = "Message Not Allowed";
            }
            
            foreach(RoomHandle room in _chatView.roomHandles)
            {
                if (room.Players.Count > 0)
                {
                    await room.SendMessage(messageToSend);
                }
            }

            return new EmptyResponse();
        }
        
        public async Task<EmptyResponse> CreateRoom ()
        {
            string roomName = _data.RoomToCreateName;
            bool keepSubscribed = false;
            List<long> players = new List<long>{_beamableAPI.User.id};
            
            var result = await _beamableAPI.Experimental.ChatService.CreateRoom(
                roomName, keepSubscribed, players);
            
            Refresh();
            
            return new EmptyResponse();
        }
        
        public async Task<EmptyResponse> LeaveRoom()
        {
            var roomInfos = await _beamableAPI.Experimental.ChatService.GetMyRooms();
            
            foreach(var roomInfo in roomInfos)
            {
                var result = await _beamableAPI.Experimental.ChatService.LeaveRoom(roomInfo.id);
            }

            Refresh();
            
            return new EmptyResponse();
        }
        
        public void Refresh()
        {
            _data.IsInRoom = _data.RoomPlayers.Count > 0;
            
            // Create new mock message 
            int messageIndex = _data.RoomMessages.Count;
            _data.MessageToSend = $"Hello World {messageIndex:000}!";
            
            // Create new mock group name
            int groupIndex = _data.RoomNames.Count;
            _data.RoomToCreateName = $"Room{groupIndex:000}";
            
            // Create temp name for pretty UI
            if (string.IsNullOrEmpty(_data.RoomToLeaveName))
            {
                _data.RoomToLeaveName = _data.RoomToCreateName;
            }
            
            // Log
            Debug.Log($"Refresh()");
            Debug.Log($"\tRoomNames.Count = {_data.RoomNames.Count}");
            Debug.Log($"\tRoomPlayers.Count = {_data.RoomPlayers.Count}");
            Debug.Log($"\tRoomMessages.Count = {_data.RoomMessages.Count}");
            Debug.Log($"\tIsInRoom = {_data.IsInRoom}");
            
            // Send relevant data to the UI for rendering
            OnRefreshed?.Invoke(_data);
        }
        
        //  Event Handlers  -------------------------------
        private void Room_OnMessageReceived(Message message)
        {
            string roomMessage = $"{message.gamerTag}: {message.content}";
            Debug.Log($"Room_OnMessageReceived() roomMessage = {roomMessage}");
            _data.RoomMessages.Add(roomMessage);
            Refresh();
        }
        
        private void Room_OnRemoved()
        {
            Debug.Log($"Room_OnRemoved");
            Refresh();
        }
    }
}

Advanced

Here are a few advanced configuration options and workflows.

Group Chat

Players can create groups, interact, and chat to group members in real-time. See Groups for more info.

Filtering Chat Messages

Beamable supports filtering chat messages to help keep the game chat safe.

public async void IsProfanity()
{
    string text = "porn"; // Ex. string is profane
    
    bool isProfanityText = true;
    try
    {
        var result = await _beamableAPI.Experimental.ChatService.ProfanityAssert(text);
        isProfanityText = false;
    } catch{}

    Debug.Log($"isProfanityText = {isProfanityText} for {text}");
} 

Updated 20 days ago


Chat


Allow players to communicate in-game

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.