Facepunch- und Netcode -ProblemeC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Facepunch- und Netcode -Probleme

Post by Anonymous »

Client trennt nach 10 Sekunden, wenn Sie versuchen, die Autokarme auszuwählen und Spieler in der Lobby mit Facepunch -Transport und NetCode für GameObjects zu laken. Ich versuche, ein Lobby -System zu erstellen, aber nichts funktioniert. Ich möchte die Autokarme und Spawn -Spieler synchronisieren, aber mein Kunde trennt nach 10 Sekunden. Wenn der Host das Spiel startet, bleibt der Kunde in der Lobby. Bitte helfen Sie. Ich habe eine Woche damit verbracht, diese Arbeit zu machen.

Code: Select all

    using UnityEngine;
using Steamworks;
using UnityEngine.UI;
using Steamworks.Data;
using System;
using System.Linq;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.Networking;
using UnityEngine.SceneManagement;
using System.Collections;

public class SteamManager : NetworkBehaviour
{
private Dictionary playerCarChoices = new Dictionary();

[Header("Menu Panels")]
[SerializeField] private GameObject mainMenuPanel;
[SerializeField] private GameObject multiplayerPanel;
[SerializeField] private GameObject lobbySettingsPanel;
[SerializeField] private GameObject lobbyPanel;

[Header("Multiplayer Panel UI")]
[SerializeField] private InputField lobbyIDInputField;
[SerializeField] private Button joinLobbyButton;

[Header("Lobby Settings Panel UI")]
[SerializeField] private InputField lobbyNameInputField;
[SerializeField] private Toggle friendsOnlyToggle;
[SerializeField] private Dropdown maxPlayersDropdown;
[SerializeField] private Button createLobbyButton;

[Header("Lobby Panel UI")]
[SerializeField] private Text lobbyNameText;
[SerializeField] private Text lobbyIDText;
[SerializeField] private Text playerCountText;
[SerializeField] private Button leaveLobbyButton;
[SerializeField] private ScrollRect playersScrollView;
[SerializeField] private GameObject playerInfoPrefab;

[Header("Car Selection UI")]
[SerializeField] private GameObject carSelectionPanel;
[SerializeField] private RawImage carPreviewImage;
[SerializeField] private Text carNameText;
[SerializeField] private Button selectCarButton;
[SerializeField] private Button nextCarButton;
[SerializeField] private Button prevCarButton;

[Header("Map Text Field")]
public string gameplayScene = "Map_001";

[Header("Car Selection")]
[SerializeField] private int currentCarIndex;
[SerializeField] private GameObject[] carObjects;
private GameObject currentCarModel;

[Header("Car Rendering")]
[SerializeField] private Camera carRenderCamera;
[SerializeField] private RenderTexture carRenderTexture;
[SerializeField] private Vector3 carCameraOffset = new Vector3(0, 2, -3);
[SerializeField] private float carRotationSpeed = 30f;

private Lobby currentLobby;
private Stack panelHistory = new Stack();
private Dictionary playerEntries = new Dictionary();

void Awake()
{
DontDestroyOnLoad(gameObject);

Debug.Log("SteamManager Awake - Initializing...");

joinLobbyButton.onClick.AddListener(JoinLobbyWithID);
createLobbyButton.onClick.AddListener(HostLobby);
leaveLobbyButton.onClick.AddListener(LeaveLobby);
selectCarButton.onClick.AddListener(ConfirmCarSelection);

maxPlayersDropdown.ClearOptions();
maxPlayersDropdown.AddOptions(Enumerable.Range(1, 8).Select(i => i.ToString()).ToList());
maxPlayersDropdown.value = 3;

ShowPanel(mainMenuPanel);

try
{
SteamClient.Init(480);
Debug.Log("SteamClient initialized succes");
}
catch (Exception e)
{
Debug.LogError("Failed to initialize SteamClient: "  + e.Message);
}

InitializeCars();
}

void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
GoBack();
}

SteamClient.RunCallbacks();
}

void OnEnable()
{
Debug.Log("Registering Steam callbacks");

SteamMatchmaking.OnLobbyCreated += LobbyCreated;
SteamMatchmaking.OnLobbyEntered += LobbyEntered;
SteamFriends.OnGameLobbyJoinRequested += LobbyJoinRequested;
SteamMatchmaking.OnLobbyMemberJoined += OnLobbyMemberJoined;
SteamMatchmaking.OnLobbyMemberLeave += OnLobbyMemberLeave;
SteamMatchmaking.OnLobbyMemberDisconnected += OnLobbyMemberLeave;
}

void OnDisable()
{
Debug.Log("Unregistering Steam callbacks");

SteamMatchmaking.OnLobbyCreated -= LobbyCreated;
SteamMatchmaking.OnLobbyEntered -= LobbyEntered;
SteamFriends.OnGameLobbyJoinRequested -= LobbyJoinRequested;
SteamMatchmaking.OnLobbyMemberJoined -= OnLobbyMemberJoined;
SteamMatchmaking.OnLobbyMemberLeave -= OnLobbyMemberLeave;
SteamMatchmaking.OnLobbyMemberDisconnected -= OnLobbyMemberLeave;
SteamClient.Shutdown();
Debug.Log("SteamClient shutdown");
}

// CarSelect
private void ChangeCar(int direction)
{
carObjects[currentCarIndex].SetActive(false);

currentCarIndex = (currentCarIndex + direction + carObjects.Length) % carObjects.Length;

carObjects[currentCarIndex].SetActive(true);
UpdateCarPreview(currentCarIndex);

Debug.Log($"Changed car to index: {currentCarIndex}");
}

private void InitializeCars()
{
if (carObjects.Length > 0)
{
foreach (var car in carObjects)
{
car.SetActive(false);
}
carObjects[0].SetActive(true);
currentCarIndex = 0;
UpdateCarPreview(0);
}
}

public void NextCar()
{
ChangeCar(1);
Debug.Log($"Next car. Current index: {currentCarIndex}");
}

public void PrevCar()
{
ChangeCar(-1);
Debug.Log($"Previous car.  Current index: {currentCarIndex}");
}

private void UpdateCarPreview(int index)
{
carNameText.text = carObjects[index].name;
SetupCarRenderCamera(carObjects[index]);
}

private void SetupCarRenderCamera(GameObject carModel)
{
if (currentCarModel != null)
{
StopAllCoroutines();
}

currentCarModel = carModel;

carRenderCamera.transform.position = carModel.transform.position + carCameraOffset;
carRenderCamera.transform.LookAt(carModel.transform);

carRenderCamera.targetTexture = carRenderTexture;
carPreviewImage.texture = carRenderTexture;

StartCoroutine(RotateCarModel());
}

private IEnumerator RotateCarModel()
{
while (currentCarModel != null)
{
currentCarModel.transform.Rotate(Vector3.up, carRotationSpeed * Time.deltaTime);
yield return null;
}
}

private void ConfirmCarSelection()
{
if (!NetworkManager.Singleton.IsClient)
{
Debug.LogError("Network not initialized!");
return;
}

PlayerPrefs.SetInt("SelectedCar", currentCarIndex);

if (PlayerCarDataHandler.Instance != null)
{
PlayerCarDataHandler.Instance.SubmitCarChoiceServerRpc(currentCarIndex);
Debug.Log($"Car choice submitted: {currentCarIndex}");
}
else
{
Debug.LogError("PlayerCarDataHandler not ready!");
}

carSelectionPanel.SetActive(false);
lobbyPanel.SetActive(true);
}

[ServerRpc(RequireOwnership = false)]
private void SubmitCarChoiceServerRpc(int carIndex, ServerRpcParams rpcParams = default)
{
ulong clientId = rpcParams.Receive.SenderClientId;
playerCarChoices[clientId] = carIndex;
Debug.Log($"Host received car choice from {clientId}: {carIndex}");
}

public bool GetPlayerCarChoice(ulong clientId, out int carIndex)
{
return playerCarChoices.TryGetValue(clientId, out carIndex);
}

public void StartGame()
{
if (!NetworkManager.Singleton.IsHost)
{
Debug.LogError("Only host can start the game!");
return;
}

if (playerCarChoices.Count != currentLobby.MemberCount)
{
Debug.LogError("Not all players have selected cars!");
return;
}

Debug.Log("Host starting game...");
NetworkManager.Singleton.SceneManager.LoadScene(gameplayScene, LoadSceneMode.Single);
}

//Menu
public void ShowPanel(GameObject panel)
{
Debug.Log($"Showing panel: {panel.name}");

if (panelHistory.Count > 0 && panelHistory.Peek() == panel)
return;

mainMenuPanel.SetActive(false);
multiplayerPanel.SetActive(false);
lobbySettingsPanel.SetActive(false);
lobbyPanel.SetActive(false);

panel.SetActive(true);

if (panel != mainMenuPanel)
{
panelHistory.Push(panel);
}
}

public void GoBack()
{
Debug.Log("Going back in menu");

if (panelHistory.Count > 0)
{
var currentPanel = panelHistory.Pop();
currentPanel.SetActive(false);

if (panelHistory.Count >  0)
{
panelHistory.Peek().SetActive(true);
}
else
{
mainMenuPanel.SetActive(true);
}
}
else
{
mainMenuPanel.SetActive(true);
}
}

// button
public void ShowMultiplayerMenu()
{
Debug.Log("Opening multiplayer menu");
ShowPanel(multiplayerPanel);
}

public void ShowLobbySettings()
{
Debug.Log("Opening lobby settings");
ShowPanel(lobbySettingsPanel);
}

public void ShowCarSelectionPanel()
{
Debug.Log("Opening Car Selection Panel");
ShowPanel(carSelectionPanel);
}

public void ExitGame()
{
Debug.Log("Exiting game");
Application.Quit();
}

private void LobbyJoinRequested(Lobby lobby, SteamId id)
{
Debug.Log($"Lobby join requested for lobby ID: {lobby.Id}");
lobby.Join();
}

private async void LobbyEntered(Lobby lobby)
{
Debug.Log($"Entered lobby: {lobby.Id} with {lobby.MemberCount} members");

currentLobby = lobby;

ClearPlayerList();

lobbyNameText.text = lobby.GetData("name");
lobbyIDText.text = "Lobby ID: " + lobby.Id.ToString();

ShowPanel(lobbyPanel);

foreach (var member in lobby.Members)
{
AddPlayerToLobbyUI(member);
}

UpdatePlayerCount();

}

private void LobbyCreated(Result result, Lobby lobby)
{
Debug.Log($"Lobby creation result: {result}");

if (result != Result.OK)
{
Debug.LogError("Failed to create lobby: "  + result);
return;
}

Debug.Log($"Successfully created lobby with ID: {lobby.Id}");

string lobbyName = lobbyNameInputField.text;
lobby.SetData("name", lobbyName);
lobby.SetPublic();
lobby.SetJoinable(true);

if (friendsOnlyToggle.isOn)
{
lobby.SetFriendsOnly();
Debug.Log("Lobby set to Friends Only");
}

Debug.Log($"Lobby settings: Name='{lobbyName}', MaxPlayers={lobby.MaxMembers}, Public={!friendsOnlyToggle.isOn}");

currentLobby = lobby;
}

private void OnLobbyMemberJoined(Lobby lobby, Friend friend)
{
Debug.Log($"Player joined: {friend.Name} (ID: {friend.Id})");

if (lobby.Id == currentLobby.Id)
{
AddPlayerToLobbyUI(friend);
UpdatePlayerCount();
}
}

private void OnLobbyMemberLeave(Lobby lobby, Friend friend)
{
Debug.Log($"Player left: {friend.Name} (ID: {friend.Id})");

if (lobby.Id == currentLobby.Id)
{
RemovePlayerFromLobbyUI(friend.Id);
UpdatePlayerCount();
}
}

private async void AddPlayerToLobbyUI(Friend friend)
{
Debug.Log($"Adding player to UI: {friend.Name}");

if (playerEntries.ContainsKey(friend.Id))
return;

var playerEntry = Instantiate(playerInfoPrefab, playersScrollView.content);
var entryUI = playerEntry.GetComponent
();

entryUI.SetUsername(friend.Name);

Debug.Log($"Fetching avatar for {friend.Name}");
var avatar = await SteamFriends.GetLargeAvatarAsync(friend.Id);
if (avatar.HasValue)
{
Debug.Log($"Avatar found for {friend.Name}");
var texture = new Texture2D(
(int)avatar.Value.Width,
(int)avatar.Value.Height,
TextureFormat.RGBA32,
false,
true);

texture.LoadRawTextureData(avatar.Value.Data);
texture.Apply();
entryUI.SetAvatar(texture);
}
else
{
Debug.Log($"No avatar found for {friend.Name}");
}

playerEntries[friend.Id] = playerEntry;
}

private void RemovePlayerFromLobbyUI(SteamId steamId)
{
Debug.Log($"Removing player from UI: {steamId}");

if (playerEntries.TryGetValue(steamId, out var entry))
{
Destroy(entry);
playerEntries.Remove(steamId);
}
}

private void ClearPlayerList()
{
Debug.Log("Clearing player list");
foreach (var entry in playerEntries.Values)
{
Destroy(entry);
}
playerEntries.Clear();
}

private void UpdatePlayerCount()
{
if (currentLobby.Id.IsValid)
{
playerCountText.text = $"Players: ({currentLobby.MemberCount}/{currentLobby.MaxMembers})";
Debug.Log($"Updated player count:  {currentLobby.MemberCount}/{currentLobby.MaxMembers}");
}
}

public async void HostLobby()
{
int maxPlayers = maxPlayersDropdown.value + 1;

try
{
var lobby = await SteamMatchmaking.CreateLobbyAsync(maxPlayers);
if (lobby.HasValue)
{
currentLobby = lobby.Value;
currentLobby.SetPublic();
currentLobby.SetJoinable(true);
currentLobby.SetData("name", lobbyNameInputField.text);

NetworkManager.Singleton.StartHost();
}
else
{
Debug.LogError("Failed to create lobby");
}
}
catch (Exception e)
{
Debug.LogError("Lobby creation error: " + e.Message);
}
}

public async void JoinLobbyWithID()
{
Debug.Log("Attempting to join lobby by ID");

if (!SteamClient.IsValid)
{
Debug.LogError("Steam client is not initialized");
return;
}

if (string.IsNullOrEmpty(lobbyIDInputField.text))
{
Debug.LogError("Lobby ID is empty");
return;
}

if (!ulong.TryParse(lobbyIDInputField.text, out ulong lobbyID))
{
Debug.LogError("Invalid Lobby ID format");
return;
}

Debug.Log($"Trying to join lobby with ID: {lobbyID}");

try
{
Lobby? lobby = await SteamMatchmaking.JoinLobbyAsync(lobbyID);

if (lobby.HasValue)
{
Debug.Log($"Successfully joined lobby ID: {lobby.Value.Id}");
NetworkManager.Singleton.StartClient();
}
else
{
Debug.LogError("Failed to join lobby - it may be private, full, or doesn't exist");
}
}
catch (Exception e)
{
Debug.LogError("Join lobby error: "  + e.Message);
}
}

public void LeaveLobby()
{
playerCarChoices.Clear();
Debug.Log("Lobby data cleared");

if (currentLobby.Id.IsValid)
{
currentLobby.Leave();
currentLobby = default;
}

if (NetworkManager.Singleton.IsHost)
{
NetworkManager.Singleton.Shutdown();
}
else if (NetworkManager.Singleton.IsClient)
{
NetworkManager.Singleton.Shutdown();
}

ShowPanel(mainMenuPanel);
}

}
< /code>
 PlayerSpawner.cs
using UnityEngine;
using Unity.Netcode;

public class PlayerSpawner : NetworkBehaviour
{
[SerializeField] private GameObject[] carPrefabs;
[SerializeField] private Transform[] spawnPoints;

private SteamManager steamManager;

public override void OnNetworkSpawn()
{
if (!IsServer) return;

Debug.Log("PlayerSpawner initialized on server");

steamManager = FindObjectOfType();
if (steamManager == null)
{
Debug.LogError("SteamManager not found!");
return;
}

SpawnAllPlayers();
}

private void SpawnAllPlayers()
{
Debug.Log($"Spawning {NetworkManager.Singleton.ConnectedClients.Count} players");

foreach (var client in NetworkManager.Singleton.ConnectedClients)
{
SpawnPlayer(client.Key);
}
}

private void SpawnPlayer(ulong clientId)
{
int spawnIndex = (int)clientId % spawnPoints.Length;

int carIndex = GetCarChoiceForPlayer(clientId);

Debug.Log($"Spawning player {clientId} with car {carIndex} at point {spawnIndex}");

GameObject car = Instantiate(
carPrefabs[carIndex],
spawnPoints[spawnIndex].position,
spawnPoints[spawnIndex].rotation
);

NetworkObject netObj = car.GetComponent();
netObj.SpawnWithOwnership(clientId);

if (clientId == NetworkManager.Singleton.LocalClientId)
{
SetupLocalPlayerCar(car);
}
}

private int GetCarChoiceForPlayer(ulong clientId)
{
if (PlayerCarDataHandler.Instance == null)
{
Debug.LogWarning("PlayerCarDataHandler not found, using default car");
return PlayerPrefs.GetInt("SelectedCar", 0);
}

int choice = PlayerCarDataHandler.Instance.GetCarChoice(clientId);
return choice != 0 ? choice : PlayerPrefs.GetInt("SelectedCar", 0);
}

private void SetupLocalPlayerCar(GameObject car)
{
car.GetComponentInChildren().enabled = true;
car.GetComponentInChildren(true).gameObject.SetActive(true);
Debug.Log("Local player car setup complete");
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post