-
-
Notifications
You must be signed in to change notification settings - Fork 141
/
NetworkManager.cs
106 lines (88 loc) · 2.8 KB
/
NetworkManager.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using Riptide.Utils;
using System;
using UnityEngine;
namespace Riptide.Demos.DedicatedClient
{
public enum ServerToClientId : ushort
{
SpawnPlayer = 1,
PlayerMovement,
}
public enum ClientToServerId : ushort
{
PlayerName = 1,
PlayerInput,
}
public class NetworkManager : MonoBehaviour
{
private static NetworkManager _singleton;
public static NetworkManager Singleton
{
get => _singleton;
private set
{
if (_singleton == null)
_singleton = value;
else if (_singleton != value)
{
Debug.Log($"{nameof(NetworkManager)} instance already exists, destroying object!");
Destroy(value);
}
}
}
[SerializeField] private string ip;
[SerializeField] private ushort port;
[SerializeField] private GameObject localPlayerPrefab;
[SerializeField] private GameObject playerPrefab;
public GameObject LocalPlayerPrefab => localPlayerPrefab;
public GameObject PlayerPrefab => playerPrefab;
public Client Client { get; private set; }
private void Awake()
{
Singleton = this;
}
private void Start()
{
RiptideLogger.Initialize(Debug.Log, Debug.Log, Debug.LogWarning, Debug.LogError, false);
Client = new Client();
Client.Connected += DidConnect;
Client.ConnectionFailed += FailedToConnect;
Client.ClientDisconnected += PlayerLeft;
Client.Disconnected += DidDisconnect;
}
private void FixedUpdate()
{
Client.Update();
}
private void OnApplicationQuit()
{
Client.Disconnect();
Client.Connected -= DidConnect;
Client.ConnectionFailed -= FailedToConnect;
Client.ClientDisconnected -= PlayerLeft;
Client.Disconnected -= DidDisconnect;
}
public void Connect()
{
Client.Connect($"{ip}:{port}");
}
private void DidConnect(object sender, EventArgs e)
{
UIManager.Singleton.SendName();
}
private void FailedToConnect(object sender, ConnectionFailedEventArgs e)
{
UIManager.Singleton.BackToMain();
}
private void PlayerLeft(object sender, ClientDisconnectedEventArgs e)
{
Destroy(Player.list[e.Id].gameObject);
}
private void DidDisconnect(object sender, DisconnectedEventArgs e)
{
UIManager.Singleton.BackToMain();
foreach (Player player in Player.list.Values)
Destroy(player.gameObject);
}
}
}