[c#] Basic Network data sending / receiving

Hello there !

I’m doing some tests with Networks and i need some help on the basics data sending/receiving.

What i want to do is to store a player’s name into an array when this player connect to the server. I already have a working connection to the server, but i don’t really understand how i can send data to the server (like a string or an integer). I tried to use RPC, but i got an error.

   private string[] sPlayersNames = new string[Constantes.MAX_PLAYERS];  //i want the player's name stored here (server side)
    private string sPlayerName;  //this is the variable that contain the player name (client side)
    NetworkView nvNetworkView = new NetworkView();
        
    void OnConnectedToServer()
    {
          Debug.Log ("Successfully connected to server !");
          //Here, i want to send the name of the player
          nvNetworkView.RPC ("SetName", RPCMode.Server, sPlayerName);  //error here
    }
            
    [RPC]
    void SetName(string sName)
    {
    	sPlayersNames[iPlayerCount] = sName;
    	Debug.Log("Name recieved !");
    }

I got the following error (client side) :

NullReferenceException
UnityEngine.NetworkView.RPC (System.String name, RPCMode mode, System.Object args) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/Networking.cs:383)
NetworkManager.OnConnectedToServer () (at Assets/Cs/NetworkManager.cs:94)

May somebody help me with that ?

Please escuse me if the question has already been asked.
Thanks for your time.

Have a wonderfull day/night :slight_smile:

Hello,

Your problem is, that you are treating a NetworkView as a standard class, when in fact, it is a component (An extension to MonoBehaviour).

Although it compiles fine, you can’t simply go new NetworkView(). Instead I suggest manually adding a NetworkView to the object and building the reference from GetComponent.
You should also add @script RequireComponent(NetworkView) so that you will never forget to add it again :wink:

Hope this helps,
Benproductions1