-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkManager.cs
More file actions
237 lines (210 loc) · 8.12 KB
/
Copy pathNetworkManager.cs
File metadata and controls
237 lines (210 loc) · 8.12 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using Microsoft.AspNetCore.SignalR.Client;
namespace Unity2D.Client
{
/// <summary>
/// Componente principal para gestionar la conexión WebSocket / SignalR entre Unity 6 (6.3 LTS) y el Backend .NET Core.
/// Diseñado para ser 100% seguro con el Hilo Principal (Main Thread) de Unity.
/// </summary>
[AddComponentMenu("Networking/Network Manager")]
[DisallowMultipleComponent]
public class NetworkManager : MonoBehaviour
{
public static NetworkManager Instance { get; private set; }
[Header("Configuración del Servidor")]
[Tooltip("URL completa del Hub de SignalR en el backend .NET")]
[SerializeField] private string serverUrl = "http://localhost:5240/hubs/game";
[Tooltip("Conectar automáticamente al iniciar la escena")]
[SerializeField] private bool autoConnectOnStart = true;
private HubConnection _hubConnection;
private readonly ConcurrentQueue<Action> _mainThreadQueue = new ConcurrentQueue<Action>();
// Eventos públicos para suscribirse desde otros scripts de Unity
public event Action<PlayerMovementDto> OnPlayerMovedReceived;
public event Action<ChatMessageDto> OnChatMessageReceived;
public event Action<string> OnPlayerLeftReceived;
public event Action OnConnected;
public event Action OnDisconnected;
public bool IsConnected => _hubConnection != null && _hubConnection.State == HubConnectionState.Connected;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
private async void Start()
{
if (autoConnectOnStart)
{
await ConnectAsync();
}
}
private void Update()
{
// Procesar acciones pendientes en el hilo principal de Unity 6 (Garantiza hilo seguro para Transform y UI)
while (_mainThreadQueue.TryDequeue(out var action))
{
action?.Invoke();
}
}
/// <summary>
/// Inicia la conexión con el servidor SignalR y registra los escuchadores de eventos.
/// </summary>
public async Task ConnectAsync()
{
if (IsConnected)
{
Debug.LogWarning("[NetworkManager] El cliente ya está conectado.");
return;
}
Debug.Log($"[NetworkManager] Conectando a {serverUrl} (Unity 6.3 LTS Client)...");
_hubConnection = new HubConnectionBuilder()
.WithUrl(serverUrl)
.WithAutomaticReconnect(new TimeSpan[] {
TimeSpan.FromSeconds(0),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
})
.Build();
// 1. Suscribirse a eventos recibidos desde el servidor (Redirigiéndolos al Hilo Principal)
_hubConnection.On<PlayerMovementDto>("OnPlayerMoved", (movement) =>
{
EnqueueOnMainThread(() =>
{
Debug.Log($"[NetworkManager] Movimiento recibido del jugador {movement.PlayerId} (X:{movement.PositionX}, Y:{movement.PositionY})");
OnPlayerMovedReceived?.Invoke(movement);
});
});
_hubConnection.On<ChatMessageDto>("OnChatMessageReceived", (chatMessage) =>
{
EnqueueOnMainThread(() =>
{
Debug.Log($"[NetworkManager] Chat recibido de {chatMessage.SenderUsername}: {chatMessage.Message}");
OnChatMessageReceived?.Invoke(chatMessage);
});
});
_hubConnection.On<string>("OnPlayerLeft", (connectionId) =>
{
EnqueueOnMainThread(() =>
{
Debug.Log($"[NetworkManager] Jugador desconectado: {connectionId}");
OnPlayerLeftReceived?.Invoke(connectionId);
});
});
// Manejo de reconexión y desconexión
_hubConnection.Reconnecting += (error) =>
{
EnqueueOnMainThread(() =>
{
Debug.LogWarning($"[NetworkManager] Perdió conexión. Intentando reconectar... Error: {error?.Message}");
});
return Task.CompletedTask;
};
_hubConnection.Reconnected += (connectionId) =>
{
EnqueueOnMainThread(() =>
{
Debug.Log($"[NetworkManager] Reconectado exitosamente en Unity 6. ConnectionId: {connectionId}");
OnConnected?.Invoke();
});
return Task.CompletedTask;
};
_hubConnection.Closed += (error) =>
{
EnqueueOnMainThread(() =>
{
Debug.LogError($"[NetworkManager] Conexión cerrada. Error: {error?.Message}");
OnDisconnected?.Invoke();
});
return Task.CompletedTask;
};
// 2. Iniciar la conexión
try
{
await _hubConnection.StartAsync();
EnqueueOnMainThread(() =>
{
Debug.Log("[NetworkManager] ¡Conectado exitosamente al servidor SignalR desde Unity 6 (6.3 LTS)! ConnectionId: " + _hubConnection.ConnectionId);
OnConnected?.Invoke();
});
}
catch (Exception ex)
{
EnqueueOnMainThread(() =>
{
Debug.LogError($"[NetworkManager] Error al conectar con el servidor: {ex.Message}");
});
}
}
/// <summary>
/// Envía las coordenadas y dirección del jugador local al servidor.
/// </summary>
public async Task SendMovementAsync(string playerId, float posX, float posY, string direction = "down")
{
if (!IsConnected) return;
var movement = new PlayerMovementDto
{
PlayerId = playerId,
PositionX = posX,
PositionY = posY,
Direction = direction
};
try
{
await _hubConnection.SendAsync("SendMovement", movement);
}
catch (Exception ex)
{
Debug.LogError($"[NetworkManager] Error al enviar movimiento: {ex.Message}");
}
}
/// <summary>
/// Envía un mensaje de chat al servidor.
/// </summary>
public async Task SendChatMessageAsync(string senderId, string username, string roomId, string message, float posX = 0, float posY = 0, bool isProximity = true)
{
if (!IsConnected) return;
var chat = new ChatMessageDto
{
SenderId = senderId,
SenderUsername = username,
RoomId = roomId,
Message = message,
SenderX = posX,
SenderY = posY,
IsProximity = isProximity
};
try
{
await _hubConnection.SendAsync("SendChatMessage", chat);
}
catch (Exception ex)
{
Debug.LogError($"[NetworkManager] Error al enviar mensaje de chat: {ex.Message}");
}
}
private void EnqueueOnMainThread(Action action)
{
if (action == null) return;
_mainThreadQueue.Enqueue(action);
}
private async void OnDestroy()
{
if (_hubConnection != null)
{
await _hubConnection.StopAsync();
await _hubConnection.DisposeAsync();
}
}
}
}