---
updatedAt: 2025-11-11T17:07:42.000Z
agentTools:
  projectIndex: https://beamable2.readme.io/llms.txt
---

# Groups - Code

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

<ul class="breadcrumb">
  <li><a href="/docs/">Docs</a></li>
  <li><a href="/docs/social-networking">Social & Networking</a></li>
  <li><a href="/docs/groups-feature-overview">Groups</a></li>
  <li>Groups - Code</li>
</ul>

<div class="links">
  <a class="link normal" href="/docs/groups-feature-overview" style={{textDecoration: 'none'}}>Overview</a>
  <a class="link active" href="/docs/groups-code" style={{textDecoration: 'none'}}>Code</a>
</div>

<HTMLBlock>{`
<style>
  
  /* Column #1 within tables */
  .markdown-body table td:nth-child(1)
  {
    width:330px !important;
    min-width:330px !important;
    max-width:330px !important;
  }
  
  
  /* Column Last within tables */
  .markdown-body table td:last-child
  {
    width:100% !important;
  }
  
</style>
`}</HTMLBlock>

## API

Unlike many Beamable <Glossary>Feature</Glossary>s, Groups do not require a specific Beamable <Glossary>Feature Prefab</Glossary> 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 <a href="https://docs.beamable.com/docs/guides-overview#asynchronous-programming">Beamable: Asynchronous Programming</a> for more info

Here are API highlights for <a href="https://csharp.cdocs.beamable.com/latest/classBeamable_1_1Api_1_1Groups_1_1GroupsService.html" target="_blank">`GroupsService`</a>.

<Table align={["left","left"]}>
  <thead>
    <tr>
      <th>
        Method Name
      </th>

      <th>
        Detail
      </th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>
        Subscribe
      </td>

      <td>
        Callback to observe changes
      </td>
    </tr>

    <tr>
      <td>
        CreateGroup
      </td>

      <td>
        Create a new group
      </td>
    </tr>

    <tr>
      <td>
        GetCurrent
      </td>

      <td>
        Get list of all current groups
      </td>
    </tr>

    <tr>
      <td>
        JoinGroup
      </td>

      <td>
        Join a group
      </td>
    </tr>

    <tr>
      <td>
        LeaveGroup
      </td>

      <td>
        Leave the current group
      </td>
    </tr>

    <tr>
      <td>
        MakeDonationRequest
      </td>

      <td>
        Request a currency donation from group
      </td>
    </tr>

    <tr>
      <td>
        Donate
      </td>

      <td>
        Send a currency donation to group member
      </td>
    </tr>

    <tr>
      <td>
        SetGroupProps
      </td>

      <td>
        Sets the <a href="https://csharp.cdocs.beamable.com/latest/classBeamable_1_1Common_1_1Api_1_1Groups_1_1GroupUpdateProperties.html" target="_blank">`GroupUpdateProperties`</a> 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
      </td>
    </tr>
  </tbody>
</Table>

## 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.

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

**Request Group Donation**

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

**Make Group Donation**

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

> 📘 Beamable SDK Examples
>
> • The following example code is available for download at <a target="_blank" href="https://www.Github.com/beamable/Beamable_SDK_Examples/">GitHub.com/Beamable\_SDK\_Examples</a>

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

```csharp GroupsServiceExample.cs
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  --------------------------------
        private async void Start()
        {
            Debug.Log("Start()");

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

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

            // 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);
                await _beamContext.Api.GroupsService.CreateGroup(groupCreateRequest);
            }

            // 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();
        }
    }
}
```

<HTMLBlock>{`
<style>
  .links {
    padding: 0 1em 1em 0;
    display: flex;
    flex-flow: row wrap;
  }

  .link {
    margin-right: 2em;
    padding: 0.3em 1.5em;
    box-sizing: border-box;
  }

  .active {
    border: 1px solid #4274f6;
    background-color: #4274f6;
    color: white;
  }

  .normal {
    background-color: white;
    border: 1px solid gray;
    cursor:pointer;
    text-decoration: none;
  }

  .normal:active {
    background-color: #c4d4ff;
  }

  .normal:hover {
    background-color: #c4d4ff;
  }

  .active:active {
    color: white;
  }

  .active:hover {
    color: white;
  }
  
  ul.breadcrumb {
    padding: 10px 16px;
    list-style: none;
  }
  ul.breadcrumb li {
    display: inline;
    font-size: 18px;
  }
  ul.breadcrumb li+li:before {
    padding: 8px;
    color: black;
    content: "/\\00a0";
  }
  ul.breadcrumb li a {
    color: #0275d8;
    text-decoration: none;
  }
  ul.breadcrumb li a:hover {
    color: #01447e;
    text-decoration: underline;
  }
  
        @media only screen and (max-width:700px){
 		    ul.breadcrumb {
    padding-top:0;
          padding-left:0;
  }
      
       .link {
    margin-right: 1em;
         margin-bottom:1em;
    }
  }
</style>
`}</HTMLBlock>

## 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](https://beamable2.readme.io/docs/chat-feature-overview) 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](https://beamable2.readme.io/docs/events-feature-overview) for more info.