When using Telepathy in Unity, follow these steps for proper integration:
- Enable Background Running: Set
Application.runInBackground = true in Awake to ensure networking continues when the window loses focus. - Configure Logging: Redirect Telepathy's internal logging to Unity's console by assigning
Debug.Log, Debug.LogWarning, and Debug.LogError to Telepathy.Logger. - Update Loop: Call
client.Tick(limit) and server.Tick(limit) inside the Unity Update() method. Even if the client/server is not currently connected/active, calling Tick is necessary to process disconnection messages. - Cleanup: Call
client.Disconnect() and server.Stop() in OnApplicationQuit() to ensure threads are shut down correctly when exiting the Editor or the build.
using System;
using UnityEngine;
public class SimpleExample : MonoBehaviour
{
Telepathy.Client client = new Telepathy.Client(1024);
Telepathy.Server server = new Telepathy.Server(1024);
void Awake()
{
// update even if window isn't focused, otherwise we don't receive.
Application.runInBackground = true;
// use Debug.Log functions for Telepathy so we can see it in the console
Telepathy.Logger.Log = Debug.Log;
Telepathy.Logger.LogWarning = Debug.LogWarning;
Telepathy.Logger.LogError = Debug.LogError;
// hook up events
client.OnConnected = () => Debug.Log("Client Connected");
client.OnData = (message) => Debug.Log("Client Data: " + BitConverter.ToString(message.Array, message.Offset, message.Count));
client.OnDisconnected = () => Debug.Log("Client Disconnected");
server.OnConnected = (connectionId) => Debug.Log(connectionId + " Connected");
server.OnData = (connectionId, message) => Debug.Log(connectionId + " Data: " + BitConverter.ToString(message.Array, message.Offset, message.Count));
server.OnDisconnected = (connectionId) => Debug.Log(connectionId + " Disconnected");
}
void Update()
{
// client
if (client.Connected)
{
// send message on key press
if (Input.GetKeyDown(KeyCode.Space))
client.Send(new ArraySegment<byte>(new byte[]{0x1}));
}
// tick to process messages
// (even if not connected so we still process disconnect messages)
client.Tick(100);
// server
if (server.Active)
{
if (Input.GetKeyDown(KeyCode.Space))
server.Send(0, new ArraySegment<byte>(new byte[]{0x2}));
}
// tick to process messages
server.Tick(100);
}
void OnGUI()
{
// client
GUI.enabled = !client.Connected;
if (GUI.Button(new Rect(0, 0, 120, 20), "Connect Client"))
client.Connect("localhost", 1337);
GUI.enabled = client.Connected;
if (GUI.Button(new Rect(130, 0, 120, 20), "Disconnect Client"))
client.Disconnect();
// server
GUI.enabled = !server.Active;
if (GUI.Button(new Rect(0, 25, 120, 20), "Start Server"))
server.Start(1337);
GUI.enabled = server.Active;
if (GUI.Button(new Rect(130, 25, 120, 20), "Stop Server"))
server.Stop();
GUI.enabled = true;
}
void OnApplicationQuit()
{
client.Disconnect();
server.Stop();
}
}