Notifications are a great way to let players know about interesting events while in game. In this section we’ll learn how to use the Nakama notification engine to send alerts and messages to players whenever a particular action triggers them.
In-app notifications can be sent from the server, then received by clients and displayed in-game. If they are marked as persistent, then the server can accept notifications even if their recipient is offline.
Remember that in-app notifications are different from push notifications you might get on your phone. They only appear when players are in-game.
Sending notifications #
First, let’s set up the server-side code to trigger notification sends.
Notifications can be bound to register hooks that fire before or after a certain event. Nakama handles the logic of detecting when events occur.
For example, if we want to reward players when they add their first friend , there is a
RegisterAfterAddFriends hook that runs after a friend is added:
Here, the function
notificationSend will deliver a notification to the user
ctx.userId when they add a new friend. In this function:
Contentis a JSON object with custom key-value pairs for whatever data you’d like to send in the notification
codeis used to specify custom notification types and can be anything desired greater than
0and below are reserved by the system
- If a notification was sent by another player, then
senderIdwill be the user ID of whoever sent it. In this case, the message was generated by the server so it should be
- If a notification has
persistent = true, then it will be sent even if the player is offline. When the player re-joins, they can then read the list of pending notifications using ListNotificationsAsync
Receiving notifications #
Now that we have a system to send notifications, let’s set up the client side.
For this we also bind a function to a hook, this time the
ReceivedNotification hook for when a notification arrives. We then use this function to process the data we sent from the server:
Here we receive the notification in the form of an
IApiNotification, which then contains all of the data we inputted to
notificationSend on the server.
content is a JSON object, we need to unpack it into a C# object. We know that the expected format is an object with a single key
reward containing a number, so we can create a class
Reward with this structure and convert
Content into it using
We then set Text objects
_descriptionText to assign with the desired subject and description.