Using Unity with Playroom Kit

🧪

The Unity SDK currently only supports Unity Web. This is an experimental technology.

Unity is the most popular game engine, it's also a great way to make web games thanks to the WebGL export option (opens in a new tab).

Playroom Kit complements Unity by simplifying the development of multiplayer games and interactive web-based applications.

Getting started

Video Tutorial

1. Install the SDK

The SDK is available as a Unity package. You can download the latest version from the releases page (opens in a new tab) (download playroomkit.unitypackage file).

To install, drag the package into your Unity project and import all files.

NPM Step

Once you have imported the package, you will need to open terminal, cd into your project directory and run the following command:

cd Assets/PlayroomKit
npm install

This will install the required dependencies for the SDK.

2. Initialize Playroom

The SDK can be initialized by calling PlayroomKit.InsertCoin in your game's Start method. You'll need to pass in a callback function that will be called when the host launches the game.

using Playroom;
// ...
 
void Start() {
    PlayroomKit.InsertCoin(new PlayroomKit.InitOptions()
    {
    maxPlayersPerRoom = 2,
    defaultPlayerStates = new() {
                    {"score", -500},
                },
    }, () =>
    {
        // The host has launched the game, you can start your game logic here.
    });
}

3. Set / Get game state

You can set and get the game state using the PlayroomKit.SetState and PlayroomKit.GetState methods. The game state is automatically synced with other players.

See the API reference for more information.

4. Export to WebGL

  • To export your game to WebGL, go to File > Build Settings and select WebGL as the platform.
  • Click Player Settings and set the Resolution and Presentation > Run In Background option to true.
  • Change WebGL Template to PWA.
  • Under Publishing Settings, set the Compression Format to None, this is to make sure the build works with most web servers including itch.io.
  • Close the Player Settings window and then click Build to export your game as a web page.
  • Once it has finished building, you can go into the output build folder and run python -m http.server to start a local web server. You can then open the game in your browser by going to http://localhost:8000.

Do note that Playroom Kit only works with WebGL builds.

Mock mode

Since the current SDK only supports Unity Web, we've introduced Mock mode - a way to test out your game's logic in Unity's Preview mode, without having to build for web every time. The mock mode doesn't connect to the Playroom server, instead it just mocks the API calls within Unity. This allows you to test out your game's logic without having to build for web every time.

The Mock mode only works in single player mode for now.

Simple Example

Use WASD or Arrow keys to move the player around. The player's position is synced with other players in real-time.

Code for this example can be found here (opens in a new tab).

API Reference

See the API reference for more information.

FAQs and Tips

How to display player's profile picture in Unity?

PlayroomPlayer.GetProfile().photo is formatted as data:image/svg+xml,{svg encoded for url}. In order to display it in Unity:

  • Remove data:image/svg+xml from the string.
  • Decode the rest using HttpUtility.UrlDecode()
  • Display the result into an SVGImage component.

Warning: Requires Unity's Vector Graphics package from com.unity.vectorgraphics which is an experimental package

 private void LoadSVG(string svgBytes) {
    // Split the string to escape the real data
    svgBytes = svgBytes.Split(",".ToCharArray(), 2)[1];
    // Decode from the URL encoding
    svgBytes = HttpUtility.UrlDecode(svgBytes);
    VectorUtils.TessellationOptions tesselationOptions = new VectorUtils.TessellationOptions();
 
    using (StringReader reader = new StringReader(svgBytes))
    {
        SVGParser.SceneInfo sceneInfo = SVGParser.ImportSVG(reader);
        tesselationOptions.MaxCordDeviation = float.MaxValue;
        tesselationOptions.MaxTanAngleDeviation = float.MaxValue;
        tesselationOptions.StepDistance = 1f;
        tesselationOptions.SamplingStepSize = 0.1f;
 
        List<VectorUtils.Geometry> geoms =
        VectorUtils.TessellateScene(sceneInfo.Scene, tesselationOptions);
 
        // Build a sprite with the tessellated geometry.
        Sprite sprite = VectorUtils.BuildSprite(geoms, 100.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
        sprite.name = "SVGimage";
        profilePicture.sprite = sprite;
    }
}

Thanks to Zy from our Discord for this tip.

How to maintain an array of Players in Unity?

By maintaining an array of Players in your game, you can execute operations over multiple players all at once, and get the latest state of multiple players. Here's a small snippet demonstrating how you can use OnPlayerJoin (opens in a new tab) and Player.OnQuit (opens in a new tab) to achieve this.

object[] players = Array.Empty<object>();
// ...
PlayroomKit.OnPlayerJoin((player) => {
  players.push(player)
  player.OnQuit(() => {
    Debug.Log($"{player.id} quit!");
    players.Where(p => p != player).ToArray();
  });
})

This may be considered an equivalent to the PlayroomKit JavaScript SDK's usePlayersList hook (opens in a new tab).

Aurea NetLayer: a higher level API for Unity

GuilhermeAlanJohann from our Discord community has created a higher level plugin (opens in a new tab) for Unity that makes it easier to use Playroom with Unity.

Features

  • Sync position and rotations of objects over the network (supports interpolation)
  • Different object authorities (Host and LocalPlayer)
  • Spawn/Unspawn objects over the network
  • Send Messages to others (including or excluding yourself)
  • RPC (...kind of). It uses Unity message system.