There is already a player for this Connection

Hello and thanks for the course first of all, has been a fly through me and now only stuck at the finishing line! :slight_smile:

Starting the Game the Host Camera is frozen and the Client can move but not set any buldings.

When I host on Unity I get following error:

There is already a player for this connection.
UnityEngine.Debug:LogError (object)
Mirror.NetworkManager:OnServerAddPlayerInternal (Mirror.NetworkConnection,Mirror.AddPlayerMessage) (at Assets/Mirror/Runtime/NetworkManager.cs:1138)
Mirror.MessagePacking/<>c__DisplayClass6_0`2<Mirror.AddPlayerMessage, Mirror.NetworkConnection>:<WrapHandler>b__0 (Mirror.NetworkConnection,Mirror.NetworkReader,int) (at Assets/Mirror/Runtime/MessagePacking.cs:118)
Mirror.NetworkServer:UnpackAndInvoke (Mirror.NetworkConnectionToClient,Mirror.NetworkReader,int) (at Assets/Mirror/Runtime/NetworkServer.cs:435)
Mirror.NetworkServer:OnTransportData (int,System.ArraySegment`1<byte>,int) (at Assets/Mirror/Runtime/NetworkServer.cs:498)
kcp2k.KcpTransport:<Awake>b__16_8 (int,System.ArraySegment`1<byte>) (at Assets/Mirror/Runtime/Transport/KCP/MirrorTransport/KcpTransport.cs:80)
kcp2k.KcpServer/<>c__DisplayClass24_0:<TickIncoming>b__1 (System.ArraySegment`1<byte>) (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpServer.cs:233)
kcp2k.KcpConnection:RawInput (byte[],int) (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpConnection.cs:492)
kcp2k.KcpServer:TickIncoming () (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpServer.cs:268)
kcp2k.KcpTransport:ServerEarlyUpdate () (at Assets/Mirror/Runtime/Transport/KCP/MirrorTransport/KcpTransport.cs:203)
Mirror.NetworkServer:NetworkEarlyUpdate () (at Assets/Mirror/Runtime/NetworkServer.cs:1699)
Mirror.NetworkLoop:NetworkEarlyUpdate () (at Assets/Mirror/Runtime/NetworkLoop.cs:185)

When Unity is the Client I get no such error but the game is stuck similarly.

I have noticed that in the RTSPlayer.cs
public override void OnStartClient() aparrently the DontDestroyOnLoad never gets called.

Edit: As additional Info I continued the tutorial and noticed that the Host reads Player 1 and Player 2 in the Lobby, however the Client sees no changes.

Any Ideas what it could be?

Thanks in advance

Hi there,
What version of Unity and Mirror are you using? Do you know at what point this error started occurring?

Hello Yitzchak_Cohen,

Thanks for your reply.
I am using Unity 2020.3.17f1 and Mirror Version 46.0.4.

I have noticed it happening at the end during this lecture and I suspect it being due to the scene change.
Earlier I suspected the Client being destroyed because I get following error with Unity being the Client:

MissingReferenceException: The object of type ‘NetworkIdentity’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Component.GetComponent[T] () (at :0)
ResourcesDisplay.Start () (at Assets/Scripts/Resources/ResourcesDisplay.cs:15)

However I have seen that with Unity being the host both player objects are under the DontDestroyOnLoad Empty Gameobject in the Hierarchy.

At a loss but still with kind regards,
seriez

Hi there, would you like to share your code from the RTS Network Manager?

Sure

using Mirror;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class RTSNetworkManager : NetworkManager
{
    [SerializeField] private GameObject unitBasePrefab = null;
    [SerializeField] private GameOverHandler gameOverHandlerPrefab = null;

    public static event Action ClientOnConnected;
    public static event Action ClientOnDisconnected;

    private bool isGameInProgress = false;

    public List<RTSPlayer> Players { get; } = new List<RTSPlayer>();

    #region Server

    public override void OnServerConnect(NetworkConnection conn)
    {
        if (!isGameInProgress) { return; }

        conn.Disconnect();
    }

    public override void OnServerDisconnect(NetworkConnection conn)
    {
        RTSPlayer player = conn.identity.GetComponent<RTSPlayer>();

        Players.Remove(player);
        
        base.OnServerDisconnect(conn);
    }

    public override void OnStopServer()
    {
        Players.Clear();

        isGameInProgress = false;
    }

    public void StartGame()
    {
        if(Players.Count < 2 ) { return; }

        isGameInProgress = true;

        ServerChangeScene("Scene_Map_01");
    }

    public override void OnServerAddPlayer(NetworkConnection conn)
    {
        base.OnServerAddPlayer(conn);

        RTSPlayer player = conn.identity.GetComponent<RTSPlayer>();

        Players.Add(player);

        player.SetDisplayName($"Makina {Players.Count}");

        player.SetTeamColor(new Color(
            UnityEngine.Random.Range(0f, 1f),
            UnityEngine.Random.Range(0f, 1f),
            UnityEngine.Random.Range(0f, 1f)
            ));

        player.SetPartyOwner(Players.Count == 1);
    }

    public override void OnServerSceneChanged(string sceneName)
    {
        if (SceneManager.GetActiveScene().name.StartsWith("Scene_Map"))
        {
            GameOverHandler gameOverHandlerInstance = Instantiate(gameOverHandlerPrefab);

            NetworkServer.Spawn(gameOverHandlerInstance.gameObject);

            foreach(RTSPlayer player in Players)
            {
                GameObject baseInstance = Instantiate(
                    unitBasePrefab, 
                    GetStartPosition().position, 
                    Quaternion.identity);

                NetworkServer.Spawn(baseInstance, player.connectionToClient);
            }
        }
    }

    #endregion

    #region Client

    public override void OnClientConnect(NetworkConnection conn)
    {
        base.OnClientConnect(conn);
        Debug.Log("Does the Client connect?");
        ClientOnConnected?.Invoke();
    }

    public override void OnClientDisconnect(NetworkConnection conn)
    {
        base.OnClientDisconnect(conn);

        ClientOnDisconnected?.Invoke();
    }

    public override void OnStopClient()
    {
        Debug.Log("Does the List Clear?");
        Players.Clear();
    }

    #endregion
}

Hmm, I can’t see anything off there. If you would like to upload your project here:
https://gdev.tv/projectupload
I can try and debug it locally.

1 Like

I have shared the project using your Link.

Thanks a lot for taking the time to try and help me! :star_struck:

Your project appears to not be setting the “Online Scene” in the networkManager. I am trying to figure out why, but having trouble. Are you able to test it with an older version of Mirror?

You can set the scene manually, but I am trying to find a place in our code to do this on the client side.
onlineScene = “Scene_Map_01”;

From what I read online, when that is not set, the client will spawn a new player object. Then when the serve connects and tries to spawn one, they conflict. Something like that anyhow…

I will attempt it using the mirror Version from the Videotutorial, when I return home from work.

If it really is related to the Mirror Version I am surprised other people have not run into this Issue yet…
Honestly my last suspicion was on wrongly implemented prefabs by me but that does not make much sense either either in regards to the error message.

Anyhow Ill reply what happens using a previous version and I am sure we will eventually figure this out :relaxed:

So I have spent another couple hours trying to figure this out. :hot_face:

I deleted the Mirror folder in the Assets and installed the one from the courses GitHub.
The Program shows other weird behaviour in that case throwing this error:

Blockquote Exception in MessageHandler: InvalidProgramException Invalid IL code in RTSPlayer:SetDisplayName (string): IL_000f: call 0x0a000028
at RTSNetworkManager.OnServerAddPlayer (Mirror.NetworkConnection conn) [0x0001f] in I:_unity_learning\SerieZ RTS\Assets\Scripts\Networking\RTSNetworkManager.cs:62
at Mirror.NetworkManager.OnServerAddPlayerInternal (Mirror.NetworkConnection conn, Mirror.AddPlayerMessage msg) [0x0007e] in I:_unity_learning\SerieZ RTS\Assets\Mirror\Runtime\NetworkManager.cs:1220
at Mirror.MessagePacker+<>c__DisplayClass6_02[T,C].<WrapHandler>b__0 (Mirror.NetworkConnection conn, Mirror.NetworkReader reader, System.Int32 channelId) [0x000ca] in I:\_unity\_learning\SerieZ RTS\Assets\Mirror\Runtime\MessagePacker.cs:120 UnityEngine.Logger:Log (UnityEngine.LogType,object) Mirror.ILoggerExtensions:LogError (UnityEngine.ILogger,object) (at Assets/Mirror/Runtime/Logging/LogFactory.cs:82) Mirror.MessagePacker/<>c__DisplayClass6_02<Mirror.AddPlayerMessage, Mirror.NetworkConnection>:b__0 (Mirror.NetworkConnection,Mirror.NetworkReader,int) (at Assets/Mirror/Runtime/MessagePacker.cs:124)
Mirror.NetworkConnection:TransportReceive (System.ArraySegment1<byte>,int) (at Assets/Mirror/Runtime/NetworkConnection.cs:251) Mirror.NetworkServer:OnDataReceived (int,System.ArraySegment1,int) (at Assets/Mirror/Runtime/NetworkServer.cs:570)
kcp2k.KcpTransport:b__12_4 (int,System.ArraySegment1<byte>) (at Assets/Mirror/Runtime/Transport/KCP/MirrorTransport/KcpTransport.cs:58) kcp2k.KcpServer/<>c__DisplayClass21_0:<Tick>b__1 (System.ArraySegment1) (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpServer.cs:185)
kcp2k.KcpConnection:TickAuthenticated (uint) (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpConnection.cs:265)
kcp2k.KcpConnection:Tick () (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpConnection.cs:285)
kcp2k.KcpServer:Tick () (at Assets/Mirror/Runtime/Transport/KCP/kcp2k/highlevel/KcpServer.cs:240)
kcp2k.KcpTransport:LateUpdate () (at Assets/Mirror/Runtime/Transport/KCP/MirrorTransport/KcpTransport.cs:108)

I tried a more recent version as well (30.1) with the Game exhibiting the same behaviour.

Further I tried for help on the Mirror Discord (using the latest version of Mirror) and a very helpful person there looked at the Code and said that in the JoinLobbyMenu.cs Join() Method the Client gets initiated again.

So joinButton is interactable after you’re already connected. You’re calling StartClient from somewhere else to get to this point…perhaps another HUD?

I personally do not see where and how it is initated twice, however the Error message does suggest this…

Okay, I finally got it working. Here is what I did:

  1. Delete the Mirror Folder.
  2. Import the latest version of Mirror.
  3. Close Unity.
  4. Delete the Library folder from the project.
  5. Reopen Unity.
  6. Go to edit → preferences, and rebuild the project files.
  7. Build and Run
  8. The game works.

I don’t know if all those steps are necessary, but I did them all just in case and it was successful. So give it a try and let me know.

1 Like

Ill check later when I return from work. However if that works that would be crazy to me! Would that be a regular debugging process for you?

Thanks a lot btw!!

That’s only normal when I am working with Mirror lol. The constant turnover with Mirror and Unity versions (and steamworks) has caused a lot of havoc on this course.

It’s basically a good ol fashion, turn if off turn it on again.

welp that did actually work! :rofl:

On the positive side I spent like 20 hours of my time trying to understand what happens that I would otherwise have not spent.

thanks a lot!!! :star_struck:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms