fgm24/Assets/Scripts/Multiplayer/NetworkedGameSetup.cs

72 lines
2.4 KiB
C#

using Assets.Scripts.Multiplayer;
using Steamworks.ServerList;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
using UnityEngine.SceneManagement;
using static UnityEditor.Experimental.GraphView.GraphView;
public class NetworkedGameSetup : NetworkBehaviour
{
[SerializeField] private GameObject PlayerPrefab;
private void Awake()
{
if (NetworkManager.Singleton == null || NetworkManager.Singleton.SceneManager == null) return;
DontDestroyOnLoad(this);
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += SceneLoaded;
}
private void SceneLoaded(string sceneName, LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut)
{
if (!sceneName.ToLower().Contains("game")) return;
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted -= SceneLoaded; // Only run once
StartSetupProcedure(clientsCompleted);
}
private void StartSetupProcedure(List<ulong> playerIds)
{
bool isOffline = NetworkSetup.serverType == ServerType.Offline;
if (isOffline)
playerIds.Add(int.MaxValue);
bool isServer = SteamManager.IsServer || LocalManager.IsServer;
GameObject[] players;
if (isServer)
players = SpawnPlayers(playerIds);
}
private GameObject[] SpawnPlayers(List<ulong> playerIds)
{
GameObject[] players = new GameObject[playerIds.Count];
for (int i = 0; i < playerIds.Count; i++)
{
GameObject player = Instantiate(PlayerPrefab, Vector2.right * i * 2, Quaternion.identity);
if (playerIds[i] != int.MaxValue)
{
player.GetComponent<NetworkObject>().SpawnAsPlayerObject(playerIds[i], true);
player.GetComponent<ReconciliationPlayerControllerMiddleman>().enabled = true;
}
else // If is offline player 2
{
var playInputScript = player.GetComponent<PlayerInput>();
playInputScript.PlayerNum = 1; // start index is 0
// Disable reconcilleration
Destroy(player.GetComponent<ReconciliationPlayerControllerMiddleman>());
}
players[i] = player;
}
return players;
}
}