This guide demonstrates how to retrieve the latest unread chat messages in a specific chat channel for your player, and get the total number of unread messages which can be displayed in the game UI.
Nakama’s cacheable cursors can be used to store a reference to where in the channel history you last read up to. This value can be stored in Unity’s PlayerPrefs.
Retrieve the cacheable cursor, defaulting to an empty string if it doesn’t already exist.
The above example only gets up to 100 new messages, but you may want to get all new messages and display a total unread message count.
To do this you need to make several calls to the ListChannelMessageAsync function, passing in an updated cursor each time. How many calls you need to make depends on the limit you set and the total number of remaining unread messages, but walking the history this way is fast.
Using a while loop you can retrieve unread messages in batches of 100, updating the cursor each time and ending once the ListChannelMessagesAsync method returns no more messages.
When all messages have been retrieved you should update the cacheable cursor value in PlayerPrefs to ensure that it is correct for the next time you perform this logic.
Below is a full example of a GetUnreadMessages method.
privateasyncTask<IList<IApiChannelMessage>>GetUnreadMessages(stringchannelId,intbatchSize=100){// Create an empty list to store unread messagesvarunreadMessages=newList<IApiChannelMessage>();// Get the current value of the cacheable cursor from PlayerPrefsvarmessagesCursor=PlayerPrefs.GetString(MESSAGES_CURSOR,string.Empty);vardone=false;while(!done){// Retrieve the next 100 messagesvarmessageList=awaitClient.ListChannelMessagesAsync(Session,channelId,batchSize,true,messagesCursor);// Add the messages to the unreadMessages listunreadMessages.AddRange(messageList.Messages);// Update the cursor ready for the next iterationmessagesCursor=messageList.CacheableCursor;// Get the number of messages retrieved this iterationvarmessageCount=messageList.Messages.Count();Debug.Log($"Got {messageCount} messages.");// If the message count this iteration matched the batch size, there may be more messages to get so continueif(messageCount==batchSize){Debug.Log("Attempting to get more messages.");continue;}// If we reached this point, there are no more messages// Update the cacheable cursor stored in PlayerPrefsPlayerPrefs.SetString(MESSAGES_CURSOR,messagesCursor);// We're doneDebug.Log($"Finished getting a total of {unreadMessages.Count} messages.");done=true;}// Return the list of unread messagesreturnunreadMessages;}
This function can be called whenever you need to update your game’s UI.
1
2
3
4
5
6
7
8
9
10
varchannelId="<SomeChannelId>";varbatchSize=100;varunreadMessages=awaitGetUnreadMessages(channelId,batchSize);UnreadMessagesText.text=$"You have {unreadMessages.Count} unread messages.";foreach(varunreadMessageinunreadMessages){// Add unreadMessage.Content to chat log as appropriate}