Unity (C#) API

Unity (C#) API

InsertCoin(InitOptions, callback)

Tell Playroom to start! Playroom Kit will then handle room creation, players joining and also let players pick their names, colors and avatars. Once host taps "Launch", the promise resolves. At this point you can start your game.

// Show Playroom UI, let it handle players joining etc and wait for host to tap "Launch"
PlayroomKit.InsertCoin(new PlayroomKit.InitOptions()
{
  maxPlayersPerRoom = 2,
  defaultPlayerStates = new() {
                  {"score", -500},
              },
}, () =>
{
  Debug.Log("Insert Coin Callback Fired! Time to play.");
});
 
// Start your game!

InitOptions parameter can have following properties:

optiontypedefaultexplanation
gameIdstringundefinedThe ID of the game from the Playroom developer portal.
streamModebooleanfalseIf true , Playroom will start in stream mode .
allowGamepadsbooleanfalseIf true , Playroom will let players play game using gamepads connected to the stream device itself. This requires streamMode to also be true.

The gamepads need to be connected to device where stream screen is running. No phones are required in this mode but are optionally allowed as an alternative controller if there aren't enough physical gamepads in the room. Players who join via phone in this mode see an on-screen Joystick.
baseUrlstringCurrent Page URLThe base URL used for generating room link that host shares with other players.
skipLobbybooleanfalseSkips the Playroom's lobby screen altogether. This is useful if you want to design your own multiplayer lobby.
roomCodestringundefinedOverride the room to join. If this is not set, a random room code is assigned. Do note that if the URL has room #r= param, that is used instead of this.
reconnectGracePeriodint0If set, Playroom will wait for the given number of milliseconds for the player to reconnect to the room after a disconnect.

If the player reconnects within the grace period, the player's state is restored. If the player does not reconnect within the grace period, the player is removed from the room and onQuit fires for the player.
maxPlayersPerRoomintundefinedIf set, Playroom will set a maximum limit for the number of players per room.

If the room is full and a new player attempts to join, the Playroom will display a default modal with a message stating that the "room is full", and the insertCoin method will throw an error with a message code ROOM_LIMIT_EXCEEDED.

If the room is full, skipLobby is set to true, and a new player is attempting to join the room, Playroom will skip the default modal but will throw an error.
avatarsArray<string>Default AvatarsAn array of URLs to images that players can pick as their avatar. This will override the default avatars system that Playroom provides.
defaultStatesDictionary<string, object>nullA dictionary containing default game states. These states are set when the room is created.
defaultPlayerStatesDictionary<string, object>nullA dictionary containing default player states. These states are set for all players when they join the room.
matchmakingMatchmakingOptions or booleanfalseAn object containing matchmaking options or just true to enable with default options.
discordbooleanfalseEnable Discord mode. See Discord Mode for more information.

GetState<T>(string key): T

Returns the current value of the given key in the game state.

ℹ️

Since C# is a static-typed language, you would have to mention the data type of the variable in place of T.

string winnerId = PlayroomKit.GetState<string>('winner');
 
var pos = players[i].GetState<Vector3>("position");

SetState(string key, T value, bool reliable = false): void

Sets the value of the given key in the game state. If reliable is true, the state is synced reliably to all players via Websockets. This is useful for game state that is critical to the game, like the winner.

If reliable is false, the state is synced via WebRTC, which is faster but less reliable. This is useful for game state that is not critical to the game, like the player's current position (you can always rely on next position update).

ℹ️

Currently tested for the following types: string, int, bool, float, Dictionary<string, T>, Vector2, Vector3 and Quaternion.

PlayroomKit.SetState('winner', 'player1');
 
// Support for built in data types such as Vectors
PlayroomKit.SetState('position', gameObject.transform.position);

OnPlayerJoin(callback)

Register a callback that will be called when a new player joins the room. The callback will be called with the player's PlayroomKit.Player object.

If a new player joins after the game has started, the callback is called with all existing PlayroomKit.Player objects, exclusively for the new player.

PlayroomKit.OnPlayerJoin((player) => {
  Debug.Log($"{player.id} joined!");
});

GetRoomCode()

Returns a 4-letter room code of the current room.

StartMatchmaking()

If you didn't pass matchmaking option in insertCoin, you can start matchmaking manually using this method.

OnDisconnect(callback)

Register a callback that will be called when the current player disconnects from the room. The callback will also be called when current player is kicked from the room.

IsHost()

Returns true if the current player is the host.

if (PlayroomKit.IsHost()) {
  // Do something only the host should do, like reading player input and setting game state
}

IsStreamScreen()

Returns true if the current screen is the stream screen; a non-player screen that is shown when the game is in stream mode .

if (PlayroomKit.IsStreamScreen()) {
  // Do something only the stream screen should do, like showing a countdown
}

WaitForState(stateKey: string, onStateSetCallback)

Call the callback only when the game state has the given key set, to any truthy value. In other words, it waits until a game state is set. This is useful for waiting for the host to set the winner, for example.

WaitForState("winner", () => {
  // Do something after waiting for the state.
}) 
 

MyPlayer() or Me()

Returns the current player's PlayroomKit.Player object.

PlayroomKit.Player player = PlayroomKit.MyPlayer();
Debug.Log($"Hello {player.GetProfile().name}!");

GetPlayer(id)

Returns a player's PlayroomKit.Player object by their ID.

PlayroomKit.Player player = PlayroomKit.GetPlayer("abcd1234");
Debug.Log($"Hello {player.GetProfile().name}!");

ResetStates(string[] keysToExclude = null, Action OnStatesReset = null)

Resets all states to the defined default states inside InitOptions. Provides optional parameters for excluding some states and a callback.

string[] statesToExclude = {"globalScores"};
PlayroomKit.ResetStates(statesToExclude, () =>
{
  // Do something after states are reset, liking starting a new round.
});

PlayroomKit.Player

A PlayroomKit.Player object represents a player in the room. In the Unity SDK, this is usually retrieved through OnPlayerJoin, MyPlayer or GetPlayer.

It has the following methods:

GetProfile(): PlayroomKit.Player.Profile

Returns the player's profile, which has the following properties:

propertytypeexplanation
namestringThe player's name.
colorUnityEngine.Color (opens in a new tab)The player's color.
photostringThe player's avatar. This is a dataURL to an image.

GetState<T>(string key): T

Returns the value of the given key in the player's state.

ℹ️

Since C# is a static-typed language, you would have to mention the data type of the variable in place of T.

int score = player.GetState<int>('score');

SetState(string key, T value, bool reliable = false)

Sets the value of the given key in the player's state.

player.SetState('score', 10);

WaitForState(stateKey: string, onStateSetCallback)

Call the callback only when the player state has the given key set, to any truthy value. In other words, it waits until a game player is set.

player.WaitForState("winner", () => {
  // Do something after waiting for the state.
}) 

Kick()

Kicks the player from the room. This is equivalent to pressing the "Kick" button in the lobby. Only the host can kick players.

player.Kick(() => {
  // Do something after kicking the player.
}) 

OnQuit(callback)

Register a callback that will be called when the player quits the room.

player.OnQuit(() => {
  Debug.Log($"{player.id} quit!");
});

MatchmakingOptions

The MatchmakingOptions object is used to specify configurations for matchmaking in the game. It consists of the following properties:

PropertyTypeDefaultDescription
waitBeforeCreatingNewRoomint5000The time in milliseconds to wait for an existing room before creating a new room.

RpcRegister(string name, Action<string, string> rpcRegisterCallback, string onResponseReturn = null)

Register a callback that will be called when a remote procedure call (RPC) with the given name is received from a player. The callback will be called with the data sent by the other player and the player.ID of the caller.

PlayroomKit.RpcRegister("Shoot", CallBackFunction, "You shot a bullet!");
 
void CallBackFunction(string data, string senderId) 
{
  var player = GetPlayer(senderId);
  Debug.Log($"{player.GetProfile().name} shoots with following damage: {data}");
}

RpcCall(string name, object data, RpcMode mode, Action callbackOnResponse)

Call a remote procedure call (RPC) with the given name and data. The mode parameter can be used to specify the mode of the RPC call. The default mode is RpcMode.ALL.

RPCs can be triggered in three different modes:

  • RpcMode.HOST: The RPC is triggered on the host only.
  • RpcMode.ALL: The RPC is triggered on all clients (including the host and the caller).
  • RpcMode.OTHERS: The RPC is triggered on all clients except the caller. You can pass a callback that will be called when the response is received.
// Using default RpcMode, which is RpcMode.ALL
var damage = 50f;
RpcCall("Shoot", damage, () =>
{
  // callback
  Debug.Log("shooting!");
});
 
// Only on Host
RpcCall("Shoot", damage, RpcMode.Host, SomeCallBack);
 
// Also supports Unity specific data types such as vectors: 
RpcCall("Scale", player.transform.scale, RpcMode.OTHERS, SomeCallBack);