Groups - Code

Allow players to create groups and interact in real-time [SOCL-Groups-02]

API

Unlike many Beamable Features, Groups do not require a specific Beamable Feature Prefab 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 GroupsService.

Method Name

Detail

Subscribe

Callback to observe changes

CreateGroup

Create a new group

GetCurrent

Get list of all current groups

JoinGroup

Join a group

LeaveGroup

Leave the current group

MakeDonationRequest

Request a currency donation from group

Donate

Send a currency donation to group member

SetGroupProps

Sets the GroupUpdateProperties including...
ā€¢ Name - Group name
ā€¢ Slogan - External-facing group slogan
ā€¢ Motd - Internal-facing message for members
ā€¢ Tag - Optional 3 letter shorthand for group
ā€¢ EnrollmentType - restricted / open / closed

  • Restricted - By invitation or application only
  • Closed - By invitation only
  • Open - Anybody can join

Examples

Here are examples which cover common programming needs.

Create Group

NOTE: The group tag must be 3 characters or less. Group tags that longer than this will throw an InvalidTag exception.

var groupCreateRequest= new GroupCreateRequest ("MyGroupName", "tag", "open", 0, 50);
await _beamContext.Api.GroupsService.CreateGroup (groupCreateRequest);

Request Group Donation

_beamContext.Api.GroupsService.MakeDonationRequest (groupId, currency);

Make Group Donation

_beamContext.Api.GroupsService.Donate (groupId, memberId, 10);

šŸ“˜

Beamable SDK Examples

ā€¢ The following example code is available for download at GitHub.com/Beamable_SDK_Examples

In this example, the player can create a group and interact.

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

namespace Beamable.Examples.Services.GroupsService
{
    /// <summary>
    /// Holds data for use in the <see cref="GroupsServiceExampleUI"/>.
    /// </summary>
    [System.Serializable]
    public class GroupsServiceExampleData
    {
        public List<string> GroupNames = new List<string>();
        public List<string> GroupPlayerNames = new List<string>();
        public List<string> RoomNames = new List<string>();
        public List<string> RoomPlayerNames = new List<string>();
        public List<string> RoomMessages = new List<string>();
        public string GroupToCreateName = "";
        public bool IsInGroup = false;
        public bool IsInRoom = false;
        public string MessageToSend = "";
      
    }
   
    [System.Serializable]
    public class RefreshedUnityEvent : UnityEvent<GroupsServiceExampleData> { }
    
    /// <summary>
    /// Demonstrates <see cref="GroupsService"/>.
    /// </summary>
    public class GroupsServiceExample : MonoBehaviour
    {
        //  Events  ---------------------------------------
        [HideInInspector]
        public RefreshedUnityEvent OnRefreshed = new RefreshedUnityEvent();
        
        //  Fields  ---------------------------------------
        private ChatView _chatView = null;
        private GroupsView _groupsView = null;
        private BeamContext _beamContext;
        private ChatService _chatService;
        private GroupsServiceExampleData _data = new GroupsServiceExampleData();
    
        //  Unity Methods  --------------------------------
        protected void Start()
        {
            Debug.Log("Start()");

            SetupBeamable();
        }
        
        //  Methods  --------------------------------------
        private async void SetupBeamable()
        {
            _beamContext = BeamContext.Default;
            await _beamContext.OnReady;
            _chatService = _beamContext.ServiceProvider.GetService<ChatService>();

            Debug.Log($"beamContext.PlayerId = {_beamContext.PlayerId}");

            // Observe GroupsService Changes
            _beamContext.Api.GroupsService.Subscribe(async groupsView =>
            {
                _groupsView = groupsView;
                _data.IsInGroup = _groupsView.Groups.Count > 0;
                
                Debug.Log("GroupsService.Subscribe 1: " + _groupsView.Groups.Count);
                
                _data.GroupNames.Clear();
                _data.GroupPlayerNames.Clear();
                foreach(var groupView in groupsView.Groups)
                {
                    string groupName = $"Name = {groupView.Group.name}, Players = {groupView.Group.members.Count}";
                    _data.GroupNames.Add(groupName);

                    foreach (var member in groupView.Group.members)
                    {
                        string groupPlayerName = $"Name = {member.gamerTag}";
                        _data.GroupPlayerNames.Add(groupPlayerName);
                    }

                    // Create a new chat room for the group
                    string roomName = $"Room For {groupView.Group.name}";
                    await _chatService.CreateRoom(roomName, false,
                        new List<long> {_beamContext.PlayerId});
                    
                }
                Refresh();
            });
            
            // Observe ChatService Changes
            _chatService.Subscribe(chatView =>
            {
                _chatView = chatView;

                int roomsWithPlayers = 0;
                _data.RoomNames.Clear();
                _data.RoomPlayerNames.Clear();
                foreach(RoomHandle room in chatView.roomHandles)
                {
                    // Optional: Only setup non-empty rooms
                    if (room.Players.Count > 0)
                    {
                        roomsWithPlayers++;
                        
                        string roomName = $"Name = {room.Name}, Players = {room.Players.Count}";
                        _data.RoomNames.Add(roomName);

                        foreach (var roomPlayerDbid in room.Players)
                        {
                            string roomPlayerName = $"Player = {roomPlayerDbid}";
                            _data.RoomPlayerNames.Add(roomPlayerName);
                        }

                        room.Subscribe().Then(_ =>
                        {
                            _data.RoomMessages.Clear();
                            foreach (var message in room.Messages)
                            {
                                string roomMessage = $"{message.gamerTag}: {message.content}";
                                _data.RoomMessages.Add(roomMessage);
                            }

                            room.OnMessageReceived += RoomHandle_OnMessageReceived;
                            Refresh();
                        });
                    }
                }

                _data.IsInRoom = roomsWithPlayers > 0;
                Debug.Log("ChatService.Subscribe 1: " + roomsWithPlayers);
                
                Refresh();
            });
        }
        
        public async Task<EmptyResponse> SendGroupMessage()
        {
            foreach(RoomHandle room in _chatView.roomHandles)
            {
                await room.SendMessage(_data.MessageToSend);
            }
            return new EmptyResponse();
        }
        
        public async Task<EmptyResponse> CreateGroup ()
        {
            // Leave any existing group
            await LeaveGroups();
            
            string groupName = _data.GroupToCreateName;
            string groupTag = "t01";
            string enrollmentType = "open";

            // Search existing group
            var groupSearchResponse = await _beamContext.Api.GroupsService.Search(groupName, 
                new List<string> {enrollmentType});
            
            // Join or Create new group
            if (groupSearchResponse.groups.Count > 0)
            {
                foreach (var group in groupSearchResponse.groups)
                {
                    var groupMembershipResponse = await _beamContext.Api.GroupsService.JoinGroup(group.id);
                }
            }
            else
            {
                var groupCreateRequest = new GroupCreateRequest(groupName, groupTag, enrollmentType, 0, 50);
                var groupCreateResponse = await _beamContext.Api.GroupsService.CreateGroup(groupCreateRequest);
                var createdGroup = groupCreateResponse.group;

                // Join new group
                await _beamContext.Api.GroupsService.JoinGroup(createdGroup.id);
            }

            // HACK: Force refresh here (0.10.1)
            // Wait (arbitrary milliseconds) for refresh to complete 
            _beamContext.Api.GroupsService.Subscribable.ForceRefresh();
            await Task.Delay(300); 
            
            Refresh();

            return new EmptyResponse();
        }
        
        public async Task<EmptyResponse> LeaveGroups()
        {
            // Leave any existing room
            await LeaveRooms();
            
            // Leave any existing groups
            foreach(var group in _groupsView.Groups)
            {
                var result = await _beamContext.Api.GroupsService.LeaveGroup(group.Group.id);
            }
            
            // HACK: Force refresh here (0.10.1)
            // Wait (arbitrary milliseconds) for refresh to complete 
            _beamContext.Api.GroupsService.Subscribable.ForceRefresh();
            await Task.Delay(300); 
            
            Refresh();
            
            return new EmptyResponse();
        }
        
        public async Task<EmptyResponse> LeaveRooms()
        {
            
            Debug.Log("_chatView 1: " + _chatView.roomHandles.Count);
            foreach(var room in _chatView.roomHandles)
            {
                var result = await _chatService.LeaveRoom(room.Id);
            }
            
            Debug.Log("_chatView 2: " + _chatView.roomHandles.Count);
            
            _data.RoomMessages.Clear();
            Refresh();
            return new EmptyResponse();
        }
        
        public void Refresh()
        {
            // Create new mock message 
            int messageIndex = _data.RoomMessages.Count + 1;
            _data.MessageToSend = $"Hello {messageIndex:000}!";
            
            // Create new mock group name
            int groupIndex = _data.GroupNames.Count + 1;
            _data.GroupToCreateName = $"Group{groupIndex:000}";

            string refreshLog = $"Refresh() ...\n" +
                                $"\n * GroupNames.Count = {_data.GroupNames.Count}" +
                                $"\n * GroupPlayerNames.Count = {_data.GroupPlayerNames.Count}" +
                                $"\n * RoomNames.Count = {_data.RoomNames.Count}" +
                                $"\n * RoomUserNames.Count = {_data.RoomPlayerNames.Count}" +
                                $"\n * IsInGroup = {_data.IsInGroup}" +
                                $"\n * IsInRoom = {_data.IsInRoom}\n\n";
            //Debug.Log(refreshLog);
          
            // Send relevant data to the UI for rendering
            OnRefreshed?.Invoke(_data);
        }
        
        //  Event Handlers  -------------------------------
        private void RoomHandle_OnMessageReceived(Message message)
        {
            string roomMessage = $"{message.gamerTag}: {message.content}";
            _data.RoomMessages.Add(roomMessage);
            Refresh();
        }
    }
}

ā—ļø

Experimental API

Please note that this feature currently includes an experimental API. Game makers will have to replace any experimental namespace when the finalized version is released.

Advanced

This section contains any advanced configuration options and workflows.

Adding Group Chat

The chat feature includes full functionality for groups. Players can send chat messages within their group. Players can also send chat messages globally, within rooms, and directly to a specific player.

See Chat for more info.

Adding Group Events

The events feature includes full functionality for groups. Players can collaborate with group members and get group rewards.

See Events for more info.


Did this page help you?