Files
dungeons/Assets/Scripts/Managers/GameManager.cs
2024-09-09 20:21:03 +02:00

131 lines
3.1 KiB
C#

using Sirenix.OdinInspector;
using System.Collections;
using Unity.Netcode;
using UnityEngine;
using Zenject;
using ParrelSync;
using UnityEngine.Events;
public class GameManager : NetworkBehaviour
{
[SerializeField]
[ReadOnly]
[Inject]
private PlayerComponent soloRig;
[SerializeField]
[ReadOnly]
private PlayerComponent multiplayerRig;
public PlayerComponent LocalPlayer => multiplayerRig ?? soloRig;
[SerializeField]
[ReadOnly]
[Inject]
private NetworkManager networkManager;
[SerializeField]
private bool autoConnectOrHost = true;
public bool IsMultiplayer => networkManager.IsHost || networkManager.IsClient;
public UnityEvent OnConnected;
public UnityEvent OnDisconnected;
private void Start()
{
networkManager.OnClientStarted += OnClientStarted;
networkManager.OnClientStopped += OnClientStopped;
networkManager.OnClientConnectedCallback += OnClientConnectedCallback;
networkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
if (autoConnectOrHost)
{
if (ClonesManager.IsClone())
{
JoinGame("");
}
else
{
HostGame();
}
}
}
public void JoinGame(string code)
{
networkManager.StartClient();
}
public void HostGame()
{
networkManager.StartHost();
}
public void LeaveGame()
{
networkManager.Shutdown(true);
//if (networkManager.IsHost)
//{
// networkManager.Shutdown(true);
//}
//else
//{
// networkManager.
//}
}
private void OnClientStarted()
{
OnConnected?.Invoke();
}
private void OnClientStopped(bool wasHost)
{
OnDisconnected?.Invoke();
}
private void OnClientConnectedCallback(ulong clientId)
{
Debug.Log($"Client-{clientId} is connected and can spawn {nameof(NetworkObject)}s.");
if (networkManager.LocalClientId == clientId)
{
StartCoroutine(SwitchSoloMultiplayerRig(false));
}
}
private IEnumerator SwitchSoloMultiplayerRig(bool toSolo)
{
yield return new WaitForEndOfFrame();
if (toSolo)
{
soloRig.Toggle(toSolo);
soloRig.Teleport(multiplayerRig.Position, multiplayerRig.Rotation);
multiplayerRig.DestroyDependencies();
multiplayerRig = null;
}
else
{
soloRig.Toggle(toSolo);
var playerObject = networkManager.LocalClient.PlayerObject;
multiplayerRig = playerObject.GetComponent<PlayerComponent>();
multiplayerRig.Teleport(soloRig.Position, soloRig.Rotation);
multiplayerRig.ToggleAudioListener(true);
}
}
private void OnClientDisconnectCallback(ulong clientId)
{
Debug.Log($"Client-{clientId} is disconnected");
if (networkManager.LocalClientId == clientId)
{
StartCoroutine(SwitchSoloMultiplayerRig(true));
}
}
}