forked from pusher/pusher-websocket-unity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PusherManager.cs
86 lines (76 loc) · 2.32 KB
/
PusherManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Threading.Tasks;
using PusherClient;
using UnityEngine;
public class PusherManager : MonoBehaviour
{
// A mutation of https://unity3d.com/learn/tutorials/projects/2d-roguelike-tutorial/writing-game-manager
public static PusherManager instance = null;
private Pusher _pusher;
private Channel _channel;
private const string APP_KEY = "APP_KEY";
private const string APP_CLUSTER = "APP_CLUSTER";
async Task Start()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
await InitialisePusher();
Console.WriteLine("Starting");
}
private async Task InitialisePusher()
{
//Environment.SetEnvironmentVariable("PREFER_DNS_IN_ADVANCE", "true");
if (_pusher == null && (APP_KEY != "APP_KEY") && (APP_CLUSTER != "APP_CLUSTER"))
{
_pusher = new Pusher(APP_KEY, new PusherOptions()
{
Cluster = APP_CLUSTER,
Encrypted = true
});
_pusher.Error += OnPusherOnError;
_pusher.ConnectionStateChanged += PusherOnConnectionStateChanged;
_pusher.Connected += PusherOnConnected;
_channel = await _pusher.SubscribeAsync("my-channel");
_channel.Subscribed += OnChannelOnSubscribed;
await _pusher.ConnectAsync();
}
else
{
Debug.LogError("APP_KEY and APP_CLUSTER must be correctly set. Find how to set it at https://dashboard.pusher.com");
}
}
private void PusherOnConnected(object sender)
{
Debug.Log("Connected");
_channel.Bind("my-event", (dynamic data) =>
{
Debug.Log("my-event received");
});
}
private void PusherOnConnectionStateChanged(object sender, ConnectionState state)
{
Debug.Log("Connection state changed");
}
private void OnPusherOnError(object s, PusherException e)
{
Debug.Log("Errored");
}
private void OnChannelOnSubscribed(object s)
{
Debug.Log("Subscribed");
}
async Task OnApplicationQuit()
{
if (_pusher != null)
{
await _pusher.DisconnectAsync();
}
}
}