Hi. I have a script with only one method OnPlayerConnected attached to a game object in online scene but the method is never called and there is no Debug.Log output neither on server nor on client. Any ideas?
As seanr said, its not going to be called on UNET. What I generally do, is have a class that controls all the network messages (simple commands and rpc, connections and disconnections), which, in server is always scanning the NetworkManager.numPlayers;
This way, if someone connects or disconnects the number of players will change and you can decide what to do…
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class NetworkMSG : NetworkBehaviour {
NetworkManager NetMngr;
NetworkClient meClient;
public int connectedPlayers=0;
void Start(){
NetMngr = GameObject.Find ("NetworkManager").GetComponent<NetworkManager> ();
if (isServer) {
NetworkServer.RegisterHandler (MsgType.Highest + 2, OnMessageRX); // if you are a server, subscribe to the message handler
GameObject.FindGameObjectWithTag ("Player").GetComponent<NetPlayerController> ().playerNum = 1;
GameObject.FindGameObjectWithTag ("Player").GetComponent<NetPlayerController> ().playerRegistered = true;
}
if(isClient){
meClient = NetMngr.client; // if you are client save your network client (to send messages to server through the handler)
}
}
//CLIENT SCRIPTS
[ClientRpc]
void RPCClient(string Garden)
{
if (!isClient)
return;
}
//Client send command to server
public void ClientSendTree(string treeData){
if (!isClient)
return;
TreeMessage Tmessage= new TreeMessage();
Tmessage.tree = treeData;
//if (!isServer) {
meClient.Send (MsgType.Highest + 2, Tmessage);
Debug.Log ("Just registred this message on network client");
//}
}
//SERVER SCRIPTS
public void Update(){
if (!isServer)
return;
if (NetMngr.numPlayers != connectedPlayers) { //detect player connection
if (NetMngr.numPlayers < 2) {
connectedPlayers = NetMngr.numPlayers;
}
if(NetMngr.numPlayers >connectedPlayers){
Debug.Log ("Player connected");
StartCoroutine(PlayerConnected (3));//wait five seconds before sending garden
connectedPlayers = NetMngr.numPlayers;
}
Debug.Log ("NetworkMSG: Players connected to host= "+(connectedPlayers-1).ToString());
RegisterClients();
}
}
IEnumerator PlayerConnected(float waitTime){
yield return new WaitForSeconds(waitTime);
Debug.Log ("NetworkMSG: Waited for client to connect, to send garden info for: " + waitTime);
TransmitGarden ();
}
public void Reset(){
if (!isServer)
return;
}
void OnMessageRX(NetworkMessage netmsg){ //receive from user
Debug.Log ("Message Received");
if (!isServer)
return;
TreeMessage msg = netmsg.ReadMessage<TreeMessage> ();//get message
}
}
public class TreeMessage : MessageBase
{
public string tree; // in the format zntm (zone, numberOfTree, TreeType, Method)
}