I’m doing some custom stuff where the player has a flag and they can create their own flag image as a png file and load it as a sprite on their flag when they join the game. They just paste the path to the file in a text field and it will add the image to their flag. I have that working good for people that are connected, but when someone connects later, I am having a heck of time figuring out how to get all clients to update the new player. I am already sending it across the network as a byte array and it is updating all of the connected clients. When a NEW client connects, all I want is for the server to tell all of the existing clients to run the same command again, since they all have the path to the png file that is local on them, that would update the new client. Any ideas at all are MUCH APPRECIATED!
You can use a SyncVar to store the data. New clients will get the SyncVar data that is most current, but will not receive any ClientRpc’s called before they join.
I don’t thing a byte[ ] can be used with a SyncVar though? I tried converting it to a “base64string” and using syncvar. Didn’t get an error, but didn’t work either. LOL. I may play with that some more.
You can put the byte array in a struct and use the struct as the SyncVar, that works. The SyncVar has to be set on the server, and then is available on clients in OnStartClient and afterwards. It won’t always be available in Awake or Start.
If you’re using the NetworkManager you could always listen in for NetworkManager.OnServerConnect which is called on the Server when a Client connects. You could then send an RPC to All Clients to update the flag.
Bear with me here, I’m a newb. When I add the rpc code to the network manager, I get this:
UNetWeaver error: Script ServerManager1 uses [ClientRpc] RpcCallChangeFlagOnClients but is not a NetworkBehaviour.
Since it uses the “NetworkManager” class, I don’t know how to fix?
Don’t use RPC nor Commands for that. You are dealing with your own data type. Its best to create a custom message and use that instead. Also, don’t use NWManager for those events, instead read states for the player object (currently more reliable way of detecting when a player is connected).
These are the unity message implementations:
https://bitbucket.org/Unity-Technologies/networking/src/78ca8544bbf4e87c310ce2a9a3fc33cdad2f9bb1/Runtime/Messages.cs?at=5.3&fileviewer=file-view-default
To send the flag upon connection you can override…
public override void OnClientConnect(NetworkConnection conn) {
//Your custom flag message using byte[] and compression(if you like)
FlagMessage message = new FlagMessage();
message.flag = someflag;
//Necessary
ClientScene.Ready(conn);
ClientScene.AddPlayer(conn, 0, message);
}
If you override OnServerAddPlayer…
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessage) {
base.OnServerAddPlayer(conn, playerControllerId);
//You can fetch the controller object for the connection here (server side)
conn.playerControllers[playerControllerId].gameObject.GetComponent<Flag>().flag = extraMessage.ReadBytes();
//Here you can set the server-side flag object for the player
//If you want you can then use a sync-var with a custom hook to load to the dummy clients.
//The ReadBytes() can be anything that the reader provides. Just neet to match the way you coded the message.
}
To send the message back to the players if RPC doens’t fit you method…
//Type is a short unique to your message, must be greater than MsgType.Highest
//Message is the actual message
NetworkServer.SendToAll(MSGID, message);
//Since the message will be sent to all clients, when registering a handler for the client, you must route the message
//to the appropriate object (unity doesn't do this).
//On the 'router' Start():
NetworkClient.RegisterHandler(MSGID, method);
private void method(NetworkMessage netMsg) {
//Get the msg
FlagMessage message = netMsg.ReadMessage<FlagMessage>();
//Find the player object
GameObject plObj = GameObject.Find(message.senderId); //You must add this manually to your message
//Get the player object to send
FlagComponent player = plObj.GetComponent<FlagComponent>();//Set the flag for the dummy
}
Thanks for the effort on posting that! So this could all be in the same script connected to my character?
All overrides should be on your ‘custom’ implementation of the network manager. The router should be a separate game object to send the messages to the correct character object.
This is what I have attached to my player right now. This all works fine and updates all clients connected with the new flag. I don’t understand how to get the byte array “data1” into the message here:
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
public class LoadFlag : NetworkBehaviour
{
byte[] data1;
Sprite Flag;
public GameObject OldFlag;
public string path;
//Create text field for path to png file
void OnGUI()
{
if (isLocalPlayer)
{
path = GUI.TextField(new Rect(200, Screen.height - 40, 400, 30), path);
}
}
//if "L" key is pressed, covert png file to byte array and send it to the CmdChangeFlag Command
void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
if (isLocalPlayer)
{
data1 = File.ReadAllBytes(path);
CmdChangeFlag(data1);
}
}
}
//Send Byte[] to server
[Command]
public void CmdChangeFlag(byte[] data)
{
data1 = data;
RpcChangeFlagOnClients(data1);
}
//Send Byte[] to clients from server and display flag on all clients
[ClientRpc]
void RpcChangeFlagOnClients(byte[] data2)
{
data1 = data2;
Texture2D texture = new Texture2D(10, 10, TextureFormat.ARGB32, false);
texture.LoadImage(data1);
texture.name = Path.GetFileNameWithoutExtension(path);
Rect rect = new Rect(20, 0, 40, 40);
Vector2 vect2 = new Vector2(1, 1);
Flag = Sprite.Create(texture, rect, vect2);
this.OldFlag.GetComponent<SpriteRenderer>().sprite = Flag;
}
}
Your code is not working the way you posted?
Yes it is working good if all clients are already connected, but when a NEW client joins, they just get the original player prefab flag, they don’t see everyone’s new flags. If there was a simple way to just run the command on all of the clients again, that would be great!
I see! This is weird! When the client connects and sends its flag, the server ‘copy’ of the instantiated prefab for the controller, should have the flag. That is what the client copies. Instead of an RPC, could you try to use a SyncVar for that data1? And use your current RPC as a hook instead?
[SyncVar(hook = "YourHookMethod")]
private byte[] flag;
private void YourHookMethod(byte[] fl){
//your stuff
}
Doing this you tell UNET that when the prefab is created it needs to download the variable from the server instead of creating a new one (for the dummy clients). You also request that when the information is set locally, the hook is to run to receive it.
Sounds great. My issue there though is that Syncvar won’t work with byte[ ]. @emrys mentioned above that I could put the byte array in a struct and send it that way. I have looked into it, but the struct stuff is kinda confusing for me too. I’ll beat on this today if I get some time and see how it goes. Thanks again for taking time to help me out!
Well, I got the struct figured out and tried the syncvar and syncvar hook and still no luck. Does the player have to have local player authority? I’m using the Opsive 3rd person controller and that is turned off by default. If I turn it on, I get this warning when the player spawns and it gets turned off again automatically. Could that be my problem?
Warning: Local Player Authority is enabled on the NetworkIdentity component. This value must be disabled.
GOT IT WORKING!!! Thanks to everyone that helped me on this. I have learned a lot with all of your suggestions!
NumberOfPlayers = NetworkManager.singleton.numPlayers;
if(NumberOfPlayersChanged!= NumberOfPlayers)
{
NumberOfPlayersChanged = NumberOfPlayers;
if (isLocalPlayer)
{
//What I want all clients to do when new player joins
data1 = File.ReadAllBytes(path);
CmdChangeFlag(data1);
}
}