# How do I use Unity's OnPlayerConnected method?

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnPlayerConnected.html

using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using UnityEngine;

public class SendData : MonoBehaviour {

void OnPlayerConnected (NetworkPlayer player) {
Debug.Log ("A player connected!");
}

}


This code, surprisingly, doesn't work!

Expected: The server prints "A player connected!" in the Unity editor debug console.

What happens: Nothing is printed. It doesn't matter if I use print() or Debug.Log().

This script is applied to a standard object in the scene. It has a NetworkIdentity.

I really don't know what else to try. The Unity documentation is very short and gives an example very similar to this. My code should be even simpler than Unity's example but it doesn't work.

• Are you sure the script is on the server and not a client ? – Uri Popov Oct 28 '17 at 9:24
• The script is on an object in the game scene opened by NetworkManager. It exists in the editor when the editor is functioning as a server. It should exist for clients too, but I figured it simply wouldn't do anything on clients. I tried changing the NetworkIdentity component to "Server Only" and it makes no difference. – Aaron Franke Oct 28 '17 at 21:36

OnPlayerConnected() and OnPlayerDisconnected() are part of the old networking API and not UNET what is currently being used. In order to achieve what you want you have to exted the Network Manager. Something like this will get you on the right track :

using UnityEngine.Networking;
using UnityEngine;

public class Send_data : NetworkManager
{

public override void OnServerConnect(NetworkConnection Conn)
{
if (Conn.hostId >= 0)
{
Debug.Log("New Player has joined");
}
}
}

• This seems to work well! Thanks. If you could take a look at my other issue, I would be grateful. I took another stab at it after applying your solution here but I still can't figure it out. – Aaron Franke Nov 1 '17 at 2:38