Code Monkey home page Code Monkey logo

cancergame's Introduction

Unity WebGL SignalR

Currently tested against and targeting Unity 2021.3.11f1 LTS.

Repo Components

  • Unity: Unity3D project with Core SignalR Plugin and example scene. For use in the editor and WebGL.
  • Server: ASP.NET Core project with SignalR hub/methods for connection that serves built Unity WebGL files.

Plugin

The Asset Package needed for adding the Plugin to a project can be found in the Releases.

Client C# Packages

To work with SignalR in the Unity Editor, package dependencies (targeting .NET Standard 2.0) are required.

First, you must have the NuGet CLI installed locally (v6.3.1 tested as functional).

Once NuGet is installed, execute the following command in PowerShell from the Plugin's lib directory to import the target .dll files.

./signalr.ps1

Client JS File

Once the Unity WebGL project is built, SignalR must be referenced in the 'head' section of index.html:

<script src="https://cdn.jsdelivr.net/npm/@microsoft/[email protected]/dist/browser/signalr.min.js"></script>

Usage

Public Methods

  • Init: Initialize a new instance of HubConnectionBuilder with the URL
  • Connect: Start the connection to the hub and bind events
  • On: Bind to the callback of a named client handler
  • Invoke: Send arguments to a named hub method
  • Stop: Stop the connection to the hub

Public Events

  • ConnectionStarted: Called on successful connection to the hub
  • ConnectionClosed: Called when the hub connection is closed

Arguments

As per the official SignalR API, up to 8 args can be received (On) and up to 10 args can be sent (Invoke).

  • The example handlers and hub methods are set to serialize/deserialize a single argument as JSON.

Example

void Start()
{
    // Initialize SignalR
    var signalR = new SignalR();
    signalR.Init("<SignalRHubURL>");

    // Handler callbacks
    signalR.On("<HandlerNameA>", (string payload) =>
    {
        // Deserialize payload A from JSON
        var json = JsonUtility.FromJson<JsonPayload>(payload);
        Debug.Log($"<HandlerNameA>: {json.message}");
    });
    signalR.On("<HandlerNameB>", (string payload) =>
    {
        // Deserialize payload B from JSON
        var json = JsonUtility.FromJson<JsonPayload>(payload);
        Debug.Log($"<HandlerNameB>: {json.message}");
    });

    // Connection callbacks
    signalR.ConnectionStarted += (object sender, ConnectionEventArgs e) =>
    {
        // Log the connected ID
        Debug.Log($"Connected: {e.ConnectionId}");

        // Send payload A to hub as JSON
        var json1 = new JsonPayload
        {
            message = "<MessageToSendA>"
        };
        signalR.Invoke("<HubMethodA>", JsonUtility.ToJson(json1));

        // Send payload B to hub as JSON
        var json2 = new JsonPayload
        {
            message = "<MessageToSendB>"
        };
        signalR.Invoke("<HubMethodB>", JsonUtility.ToJson(json2));
    };
    signalR.ConnectionClosed += (object sender, ConnectionEventArgs e) =>
    {
        // Log the disconnected ID
        Debug.Log($"Disconnected: {e.ConnectionId}");
    };

    signalR.Connect();
}

[Serializable]
public class JsonPayload
{
    public string message;
}

References

cancergame's People

Contributors

jingchengyang4 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.