Skip to content
Download all docs .md

Multiplayer Pong Example (Unity C#)

This page builds a two-player Pong game in Unity, from a new empty project to a match against another player. It is one C# script and one empty GameObject; the court is drawn with OnGUI, so there are no sprites, prefabs or scene setup to get wrong.

Before you start

You need:

  • A GameFuse account and a game. The game's page on the dashboard shows its game ID and API token.
  • Multiplayer switched on for the game, and its upload key. Both are on the game's Multiplayer tab.
  • Node.js 20 or later, for the gamefuse command that uploads your room code.

The game has two halves:

Part Runs on What it does
Room code (room.js) GameFuse's multiplayer servers Moves the ball, bounces it, keeps the score, picks the winner. The same file for every engine.
Game client Each player's computer Draws the court, sends where the player's paddle is, shows what the room sends back.

The room owns the ball and the score, so a player cannot cheat by changing them. Each player only sends one thing: where their paddle is.

Desktop, mobile and the editor, not WebGL

The C# multiplayer client uses System.Net.WebSockets, which Unity WebGL builds do not have. For a browser game, see the JavaScript version.

Make the project

In Unity Hub, make a new project from the Universal 2D template (any template works) and call it Pong.

Add the GameFuse SDK

In Unity, open Window > Package Manager, press +, choose Add package from git URL and paste:

https://github.com/GameFuseCo/game-fuse-cs.git?path=com.gamefuse.sdk

The multiplayer client is in the GameFuseCSharp namespace.

Write the room code

The room code is one JavaScript file that GameFuse runs for every match. It is the same for every engine, so a Unity player can play against a browser, Unity or Unreal player.

Install the gamefuse command once:

npm i -g gamefuse

In your project folder, make the room code folder. --game-mode pong is the queue name the game client joins; put in your own game ID:

gamefuse multiplayer init --game-name pong --game-mode pong --game 123

That makes a folder called pong-pong-gamefuse-multiplayer with a starter room.js and a .env file. Replace pong-pong-gamefuse-multiplayer/room.js with this:

// Pong for two players. The room owns the ball and the score, so nobody can cheat;
// each player only sends where their own paddle is.
// This is the room code used by every "Multiplayer Pong Example" page in the docs.

const WIDTH = 800;
const HEIGHT = 500;
const PADDLE_HEIGHT = 90;
const PADDLE_X = 30;      // how far each paddle is from its wall
const BALL_SPEED = 300;   // pixels per second when served
const POINTS_TO_WIN = 5;

export default {
  config: {
    minPlayers: 2,
    maxPlayers: 2,
    tickRate: 30,         // update() runs 30 times a second
    reconnectSeconds: 15, // a dropped player gets 15 seconds to come back
  },

  start(room) {
    const [left, right] = room.players; // the first player in is on the left
    room.state.sides = { [left.id]: 'left', [right.id]: 'right' };
    room.state.paddles = { left: HEIGHT / 2, right: HEIGHT / 2 };
    room.state.score = { left: 0, right: 0 };
    serve(room, 1);

    // Tell each player which side they are on.
    room.send(left, 'start', { side: 'left', width: WIDTH, height: HEIGHT, pointsToWin: POINTS_TO_WIN });
    room.send(right, 'start', { side: 'right', width: WIDTH, height: HEIGHT, pointsToWin: POINTS_TO_WIN });
  },

  update(room, dt) {
    const s = room.state;
    if (!s.ball || s.over) return;
    const ball = s.ball;

    ball.x += ball.vx * dt;
    ball.y += ball.vy * dt;

    // Bounce off the top and bottom walls.
    if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
    if (ball.y > HEIGHT) { ball.y = HEIGHT; ball.vy = -Math.abs(ball.vy); }

    // Bounce off a paddle. Hitting near the end of a paddle sends the ball off at an angle.
    hitPaddle(ball, PADDLE_X, s.paddles.left, -1);
    hitPaddle(ball, WIDTH - PADDLE_X, s.paddles.right, 1);

    // Past a paddle: a point for the other side.
    if (ball.x < 0) point(room, 'right');
    if (ball.x > WIDTH) point(room, 'left');

    room.broadcast('state', {
      ball: { x: Math.round(ball.x), y: Math.round(ball.y) },
      left: Math.round(s.paddles.left),
      right: Math.round(s.paddles.right),
      score: s.score,
    });
  },

  message(room, player, type, data) {
    if (type !== 'paddle' || !room.state.sides) return;
    const side = room.state.sides[player.id];
    const y = Number(data && data.y);
    if (!side || !Number.isFinite(y)) return;
    room.state.paddles[side] = Math.max(PADDLE_HEIGHT / 2, Math.min(HEIGHT - PADDLE_HEIGHT / 2, y));
  },

  playerLeft(room, player, how) {
    // A player quit, or dropped and did not come back in time: the other one wins.
    if (!room.state.sides || room.state.over) return;
    const other = room.players.find((p) => p.id !== player.id);
    if (other) finish(room, other);
  },

  async gameEnd(room, result) {
    if (result.winnerId) await room.gamefuse.users.addScore(result.winnerId, 1);
  },
};

function serve(room, direction) {
  room.state.ball = {
    x: WIDTH / 2,
    y: HEIGHT / 2,
    vx: BALL_SPEED * direction,
    vy: BALL_SPEED * (Math.random() - 0.5),
  };
}

// side: -1 for the left paddle, 1 for the right. Only bounces a ball moving toward that paddle.
function hitPaddle(ball, paddleX, paddleY, side) {
  const movingToward = side < 0 ? ball.vx < 0 : ball.vx > 0;
  const closeInX = Math.abs(ball.x - paddleX) < 12;
  const closeInY = Math.abs(ball.y - paddleY) < PADDLE_HEIGHT / 2 + 6;
  if (!movingToward || !closeInX || !closeInY) return;
  ball.vx = -ball.vx * 1.05;                  // a little faster every hit
  ball.vy += (ball.y - paddleY) * 5;
}

function point(room, side) {
  const s = room.state;
  s.score[side] += 1;
  room.broadcast('point', { side, score: s.score });

  if (s.score[side] >= POINTS_TO_WIN) {
    const winnerId = Object.keys(s.sides).find((id) => s.sides[id] === side);
    finish(room, room.players.find((p) => String(p.id) === winnerId));
    return;
  }
  serve(room, side === 'left' ? 1 : -1);      // serve toward the player who lost the point
}

function finish(room, winner) {
  room.state.over = true;
  const side = room.state.sides[winner.id];
  room.broadcast('winner', { side, name: winner.name });
  room.end({ winnerId: winner.id });
}

What each part does:

  • config asks for 2 players, runs update 30 times a second, and holds a dropped player's seat for 15 seconds.
  • start runs once both players are in. The first player in plays on the left. Each player is told their side.
  • update moves the ball, bounces it off the walls and paddles, scores points, and sends every player a state message: the ball, both paddles and the score.
  • message takes a player's paddle message and moves only that player's paddle, kept on the court.
  • playerLeft gives the match to the other player if someone quits or does not come back in time.
  • gameEnd adds 1 to the winner's GameFuse score after room.end.

The messages, which every game client below uses:

Message Who sends it Data
start room, to each player { side: "left" or "right", width: 800, height: 500, pointsToWin: 5 }
state room, 30 times a second { ball: { x, y }, left, right, score: { left, right } } (left and right are the middles of the paddles)
point room { side, score }: who scored
winner room { side, name }
paddle each player, up to 20 times a second { y }: the middle of their paddle, 45 to 455

The court is 800 by 500, with (0, 0) at the top left. The paddles are 90 tall and 30 in from each wall.

Make the room code folder next to your Unity project folder (or inside it, outside Assets), so Unity does not try to import the JavaScript.

Upload the room code to GameFuse

Open the .env file that init made in your project folder and put in your upload key from the game's Multiplayer tab:

# .env  (keep it out of git: it holds a secret)
GAMEFUSE_UPLOAD_KEY=mpk_your_upload_key
GAMEFUSE_GAME_ID=123

init already added .env to your .gitignore. Never put the upload key in your game.

Check the room code, then upload it:

gamefuse multiplayer validate
gamefuse multiplayer deploy

validate runs the same check GameFuse's servers run and uploads nothing. deploy checks, uploads and makes it the live version for the pong queue. New matches use it at once.

To see what your room code logs while you play:

gamefuse multiplayer logs --follow

Write the game client

In the Project window, make a C# script in Assets called PongGame and replace it with this. Put in your own game ID and API token:

using System;
using System.Collections.Generic;
using GameFuseCSharp;
using UnityEngine;

// Two-player Pong on GameFuse Multiplayer. Add this to an empty GameObject and press Play.
public class PongGame : MonoBehaviour
{
    const string GameId = "123";                     // your game's ID
    const string GameToken = "your-game-api-token";  // your game's API token

    GameFuseMultiplayer multiplayer;
    GameFuseRoom room;

    string mySide;                       // "left" or "right", from the room's "start" message
    string status = "Signing in...";

    // What the room last sent, in court pixels (the court is 800 x 500, 0,0 at the top left)
    Vector2 ball = new Vector2(400, 250);
    float leftPaddle = 250, rightPaddle = 250;
    long leftScore, rightScore;

    float myPaddle = 250;                // where my mouse says my paddle is
    float sendTimer;

    void Start()
    {
        GameFuse.SetUpGame(GameId, GameToken, OnGameSetUp);
    }

    async void OnGameSetUp(string message, bool hasError)
    {
        if (hasError) { status = message; return; }

        multiplayer = GameFuseMultiplayerUnity.Create();   // runs room events on Unity's main thread
        try
        {
            if (!multiplayer.IsSignedIn) await multiplayer.SignInAsGuest();
            status = "Waiting for another player...";
            room = await multiplayer.JoinQueue("pong", new Dictionary<string, object> { { "clientVersion", "1" } });
        }
        catch (Exception e)
        {
            status = e.Message;
            return;
        }

        room.OnMessage(OnRoomMessage);
        room.OnReconnecting(() => status = "Connection lost. Getting back in...");
        room.OnReconnected(() => status = "Back in.");
        room.OnClosed((reason, detail) =>
        {
            if (reason == "no_match") status = "Nobody else is online. Press Play to try again.";
        });
    }

    void OnRoomMessage(string type, object data)
    {
        var message = data as Dictionary<string, object>;

        if (type == "start")
        {
            mySide = (string)message["side"];
            status = "You are on the " + mySide + ". First to " + message["pointsToWin"] + " wins.";
        }
        else if (type == "state")
        {
            var ballData = (Dictionary<string, object>)message["ball"];
            ball = new Vector2(Convert.ToSingle(ballData["x"]), Convert.ToSingle(ballData["y"]));
            leftPaddle = Convert.ToSingle(message["left"]);
            rightPaddle = Convert.ToSingle(message["right"]);

            var score = (Dictionary<string, object>)message["score"];
            leftScore = Convert.ToInt64(score["left"]);
            rightScore = Convert.ToInt64(score["right"]);
        }
        else if (type == "winner")
        {
            status = (string)message["side"] == mySide ? "You win!" : message["name"] + " wins.";
        }
    }

    void Update()
    {
        if (room == null || room.IsClosed || mySide == null) return;

        // Send my paddle 20 times a second (the room accepts up to 60 messages a second).
        sendTimer += Time.deltaTime;
        if (sendTimer >= 0.05f)
        {
            sendTimer = 0;
            room.Send("paddle", new Dictionary<string, object> { { "y", (long)Mathf.Round(myPaddle) } });
        }
    }

    // Draws the court scaled to the window, and reads the mouse.
    void OnGUI()
    {
        float scale = Mathf.Min(Screen.width / 800f, (Screen.height - 40) / 500f);
        var origin = new Vector2((Screen.width - 800 * scale) / 2, 40);

        // The mouse's height over the court is my paddle.
        myPaddle = Mathf.Clamp((Event.current.mousePosition.y - origin.y) / scale, 45, 455);

        GUI.Label(new Rect(10, 10, Screen.width - 20, 24), status);

        Box(0, 0, 800, 500, Color.black, scale, origin);
        float left = mySide == "left" ? myPaddle : leftPaddle;     // my own paddle follows my mouse at once
        float right = mySide == "right" ? myPaddle : rightPaddle;
        Box(24, left - 45, 12, 90, new Color(0.56f, 0.61f, 1f), scale, origin);
        Box(764, right - 45, 12, 90, new Color(1f, 0.54f, 0.3f), scale, origin);
        Box(ball.x - 5, ball.y - 5, 10, 10, Color.white, scale, origin);

        GUI.Label(new Rect(origin.x + 330 * scale, origin.y + 10, 200, 30), leftScore + "      " + rightScore);
    }

    // A filled rectangle at court position x, y.
    static void Box(float x, float y, float width, float height, Color color, float scale, Vector2 origin)
    {
        GUI.color = color;
        GUI.DrawTexture(new Rect(origin.x + x * scale, origin.y + y * scale, width * scale, height * scale), Texture2D.whiteTexture);
        GUI.color = Color.white;
    }

    void OnDestroy()
    {
        if (room != null && !room.IsClosed) room.Leave();
    }
}

Then in the Hierarchy, make an empty GameObject (GameObject > Create Empty), name it Pong, and drag the PongGame script onto it.

Play it

Press Play. The game signs in and shows "Waiting for another player...".

You need a second player who is not the same guest. The guest is saved in PlayerPrefs, so a build on the same computer may be the same player. The quickest opponents:

  • the JavaScript version in a browser, with the same game ID and token;
  • the computer player from the REST API version: node bot.js;
  • or a build of this project on a second computer.

They all join the same pong queue, so they are matched with your Unity game. Move the mouse up and down over the court. First to 5 wins, and the winner gets 1 point on their GameFuse score.

Next