Currently tested against and targeting Unity 2022.3.21f1 LTS.
- 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.
The Asset Package needed for adding the Plugin to a project can be found in the Releases.
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.9.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
Once the Unity WebGL project is built, SignalR must be referenced in the 'head' section of index.html:
<script src="https://www.unpkg.com/@microsoft/[email protected]/dist/browser/signalr.min.js"></script>
- 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
- ConnectionStarted: Called on successful connection to the hub
- ConnectionClosed: Called when the hub connection is closed
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 handler and hub method are set to serialize/deserialize a single argument as JSON.
void Start()
{
// Initialize SignalR
var signalR = new SignalR();
signalR.Init("<SignalRHubURL>");
// Handler callback
signalR.On("<HandlerName>", (string payload) =>
{
// Deserialize payload from JSON
var json = JsonUtility.FromJson<JsonPayload>(payload);
Debug.Log($"<HandlerName>: {json.message}");
});
// Connection callback
signalR.ConnectionStarted += (object sender, ConnectionEventArgs e) =>
{
// Log the connected ID
Debug.Log($"Connected: {e.ConnectionId}");
// Send payload to hub as JSON
var json1 = new JsonPayload
{
message = "<MessageToSend>"
};
signalR.Invoke("<HubMethod>", JsonUtility.ToJson(json1));
};
signalR.ConnectionClosed += (object sender, ConnectionEventArgs e) =>
{
// Log the disconnected ID
Debug.Log($"Disconnected: {e.ConnectionId}");
};
signalR.Connect();
}
[Serializable]
public class JsonPayload
{
public string message;
}