#Can anyone help with multiplayer network sync issue

1 messages · Page 1 of 1 (latest)

normal void
#

fixed the movement but second player not appearing this is my network script: using UnityEngine;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using System.Net.Sockets;

public class NetworkAutoStarter : MonoBehaviour
{
[SerializeField] private string address = "127.0.0.1";
[SerializeField] private ushort basePort = 7777;
[SerializeField] private int portRange = 50;

private void Start()
{
    var nm = NetworkManager.Singleton;
    if (nm == null)
    {
        Debug.LogError("❌ No NetworkManager found in scene!");
        return;
    }

    var utp = nm.GetComponent<UnityTransport>();
    if (utp == null)
    {
        Debug.LogError("❌ No UnityTransport found on NetworkManager!");
        return;
    }

    ushort hostPort = basePort;
    ushort clientPort = FindFreePort((ushort)(basePort + 1), (ushort)(basePort + portRange));
    bool canHost = IsPortFree(hostPort);

    if (canHost)
    {
        // 🟢 HOST
        utp.SetConnectionData(address, hostPort);
        nm.StartHost();
        Debug.Log($"🟢 HOST started on {address}:{hostPort}");
    }
    else
    {
        // 🔵 CLIENT
        utp.SetConnectionData(address, hostPort);
        utp.ConnectionData.Port = clientPort;
        nm.StartClient();
        Debug.Log($"🔵 CLIENT started (local port {clientPort}) connecting to {address}:{hostPort}");
    }
}

private bool IsPortFree(ushort port)
{
    try
    {
        using (var udp = new UdpClient(port))
            return true;
    }
    catch (SocketException)
    {
        return false;
    }
}

private ushort FindFreePort(ushort start, ushort end)
{
    for (ushort p = start; p <= end; p++)
        if (IsPortFree(p)) return p;

    Debug.LogWarning("⚠️ No free ports found, using basePort instead.");
    return start;
}

}