Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by AurimasBlazulionis · Mar 15, 2015 at 09:38 AM · networkingserializationrpc

Problem with networking

Hello, I was doing a multiplayer menu script, which at same time saves player data(position, health, cash...) and serializes to a file. Everything works fine on server, but on client side nothing works(client doesn't receive any data because of RPC errors, no line numbers were specified, also these errors shew up on a client, not server).

alt text

Anyways, here's my code:

 #pragma strict
 import System;
 import System.Runtime.Serialization.Formatters.Binary;
 import System.IO;
 
 var clientspawn : GameObject;
 var playerPref : GameObject;
 var nickname : String = "";
 private var nickname1 : String = "";
 var ip : String = "127.0.0.1";
 var port : String = "25001";
 
 public var gamename : String = "Game1";
 var myChar : GameObject;
 var playerGUID : String;
 
 var gameName : String = "TDGTutorial";
 
 var password : String;
 var usePassword : boolean;
 var useNAT : boolean;
 var useMasterServer : boolean;
 
 var chosenProfile : int;
 //UI panels
 var chooseProfilePanel : GameObject;
 var createProfilePanel : GameObject;
 var menuPanel : GameObject;
 var createServerPanel : GameObject;
 var connectToServerPanel : GameObject;
 var loginPanel : GameObject;
 var profileTextList : UI.Text[];
 
 var createServerPort : int;
 var connectPort : int;
 var connectIP : String;
 
 function Start(){
     refreshProfiles();
 }
 
 function startServer(){ //starts the server
     Debug.Log(gamename);
     if(usePassword)
         Network.incomingPassword = password;
         
     Network.InitializeServer(16,System.Int32.Parse(port), useNAT);
     
     if(useMasterServer)
         MasterServer.RegisterHost(gameName, gamename, " this is a tutorial");
 }
 
 
 function OnServerInitialized(){ //This is used once server is started
     Debug.Log("Server initialized!");
     GetComponent(ToggleCreator).enabled=true;
     createServerPanel.SetActive(false);
     spawnPlayer();
     Debug.Log("Player Spawned!");
     if(Network.isServer)
         RequestPlayerData(playerGUID, myChar.GetComponent.<NetworkView>().owner, true);
     Debug.Log("Requested the data! "+playerGUID+"  "+ myChar.GetComponent.<NetworkView>().owner);
     while(true){
         yield WaitForSeconds(60);
         Debug.Log("Saving all players data!");
         GetComponent.<NetworkView>().RPC("RequestPlayerStatsData", RPCMode.All);
         SavePlayerData(playerGUID, myChar.transform.position, myChar.GetComponent(MoneySystem).money, myChar.GetComponent(LifeSystem).health, myChar.GetComponent(Shooting).bulletsCur, myChar.GetComponent(Shooting).bulletsClipCur, myChar.GetComponent(CarSystem).availableCars);
     }
 }
 function OnConnectedToServer(){ //This is used when client successfully connects to server
     loginPanel.SetActive(false);
     connectToServerPanel.SetActive(false);
     spawnPlayer();
     if(Network.isClient)
         GetComponent.<NetworkView>().RPC("RequestPlayerData", RPCMode.Server, playerGUID, myChar.GetComponent.<NetworkView>().owner, false);
     
 }
 
 function disconnect(){ //Disconnect from server
     if(Network.isServer){
         GetComponent.<NetworkView>().RPC("RequestPlayerStatsData", RPCMode.All);
         SavePlayerData(playerGUID, myChar.transform.position, myChar.GetComponent(MoneySystem).money, myChar.GetComponent(LifeSystem).health, myChar.GetComponent(Shooting).bulletsCur, myChar.GetComponent(Shooting).bulletsClipCur, myChar.GetComponent(CarSystem).availableCars);    
     }
     else if(Network.isClient)
         GetComponent.<NetworkView>().RPC("SavePlayerData", RPCMode.Server, playerGUID, myChar.transform.position, myChar.GetComponent(MoneySystem).money, myChar.GetComponent(LifeSystem).health, myChar.GetComponent(Shooting).bulletsCur, myChar.GetComponent(Shooting).bulletsClipCur, myChar.GetComponent(CarSystem).availableCars);
     Network.Destroy(myChar);
     Network.Disconnect();
     if(Network.isServer)
         MasterServer.UnregisterHost();
     Application.LoadLevel(Application.loadedLevel);
 }
 
 function quitApplication(){
     if(Network.isServer){
         GetComponent.<NetworkView>().RPC("RequestPlayerStatsData", RPCMode.All);
         SavePlayerData(playerGUID, myChar.transform.position, myChar.GetComponent(MoneySystem).money, myChar.GetComponent(LifeSystem).health, myChar.GetComponent(Shooting).bulletsCur, myChar.GetComponent(Shooting).bulletsClipCur, myChar.GetComponent(CarSystem).availableCars);
     }
     else if(Network.isClient)
         GetComponent.<NetworkView>().RPC("SavePlayerData", RPCMode.Server, playerGUID, myChar.transform.position, myChar.GetComponent(MoneySystem).money, myChar.GetComponent(LifeSystem).health, myChar.GetComponent(Shooting).bulletsCur, myChar.GetComponent(Shooting).bulletsClipCur, myChar.GetComponent(CarSystem).availableCars);
     Network.Destroy(myChar);
     Network.Disconnect();
     if(Network.isServer)
         MasterServer.UnregisterHost();
     Application.Quit();
 }
 
 function spawnPlayer() { //spawns player in spawn gameobject position
     myChar = Network.Instantiate(playerPref, clientspawn.transform.position, Quaternion.identity, 0);
 }
 
 function DisableCharacterMovement(state : boolean){
     if(myChar != null){
         myChar.GetComponent(CharacterMove).enabled = state;
         myChar.GetComponent(EnterCar).minimapCam.SetActive(state);
         myChar.GetComponent(EnterCar).enabled = state;
         myChar.GetComponent(Shooting).enabled = state;
         myChar.GetComponent(Shooting).aiming = false;
         myChar.GetComponent(Shooting).shooting = false;
         myChar.GetComponent(MouseLook).enabled = state;
         myChar.GetComponentInChildren(SpineRot).enabled = state;
     }
 }
 
 function chooseProfile(profileNum : int){
     if(System.IO.File.Exists(Application.persistentDataPath + "/profile"+profileNum+".dat")){
         var bf : BinaryFormatter = new BinaryFormatter();
         var file : FileStream = File.Open(Application.persistentDataPath + "/profile"+profileNum+".dat", FileMode.Open);    
         var data : playerProfile = bf.Deserialize(file) as playerProfile;
         file.Close();
         
         playerGUID = data.GUID;
         nickname = data.nickname;
         Debug.Log("Read the file! Nickname: "+data.nickname+", and GUID is "+data.GUID);
         chooseProfilePanel.SetActive(false);
         menuPanel.SetActive(true);
     }
     else{
         chosenProfile = profileNum;
         chooseProfilePanel.SetActive(false);
         createProfilePanel.SetActive(true);
     }
 }
 
 function saveProfile(){
     var bf : BinaryFormatter = new BinaryFormatter();
     var file : FileStream = File.Create(Application.persistentDataPath + "/profile"+chosenProfile+".dat");
     var data : playerProfile = new playerProfile();
     
     data.GUID = System.Guid.NewGuid().ToString();
     playerGUID = data.GUID;
     data.nickname = nickname;
     
     bf.Serialize(file, data);
     file.Close();
     
     createProfilePanel.SetActive(false);
     menuPanel.SetActive(true);
 }
 
 function deleteProfile(profileNum : int){
     File.Delete(Application.persistentDataPath + "/profile"+profileNum+".dat");
     refreshProfiles();
 }
 
 function refreshProfiles(){
     for(var i = 1; i <= profileTextList.length; i++){
         profileTextList[i-1].text = getProfileNickname(i);
     }
 }
 
 function getProfileNickname(profileNum : int) : String{
     if(System.IO.File.Exists(Application.persistentDataPath + "/profile"+profileNum+".dat")){
         var bf : BinaryFormatter = new BinaryFormatter();
         var file : FileStream = File.Open(Application.persistentDataPath + "/profile"+profileNum+".dat", FileMode.Open);    
         var data : playerProfile = bf.Deserialize(file) as playerProfile;
         file.Close();
         
         return data.nickname;
     }
     else{
         return "-Empty Profile-";
     }
 }
 
 function updateNickname(name : UI.InputField){
     nickname = name.text;
 }
 
 function updatePassword(i : UI.Toggle){
     usePassword = i.isOn;
 }
 
 function updateNAT(i : UI.Toggle){
     useNAT = i.isOn;
 }
 
 function updateServerPassword(i : UI.InputField){
     password = i.text;
 }
 
 function updatePort(i : UI.InputField){
     port = i.text;
 }
 
 function updateConnectIP(i : UI.InputField){
     ip = i.text;
 }
 
 function updateMasterServer(i : Component){
     useMasterServer = i;
 }
 
 function connectToServer(){
     if(password == "")
         Network.Connect(ip, parseInt(port));
     else
         Network.Connect(ip, parseInt(port), password);
 }
 
 function OnFailedToConnect(error : NetworkConnectionError) {
      Debug.Log("Could not connect to server: " + error);
  
      if(error == NetworkConnectionError.InvalidPassword){
          Debug.Log("Invalid Password Entered");
          loginPanel.SetActive(true);
          connectToServerPanel.SetActive(false);
      }
      else
          Debug.Log("Another error occured");
 }
 
 
 
 @RPC
 function RequestPlayerData(GUID : String, NP : NetworkPlayer, isServer : boolean){
     Debug.Log("Got request from: "+NP+" "+NP.ipAddress+" GUID: " + GUID);
     if(System.IO.File.Exists(Application.persistentDataPath + "/player_"+GUID+".dat")){
         Debug.Log("file exists!");
         var bf : BinaryFormatter = new BinaryFormatter();
         var file : FileStream = File.Open(Application.persistentDataPath + "/player_"+GUID+".dat", FileMode.Open);    
         var data : playerData = bf.Deserialize(file) as playerData;
         file.Close();
         Debug.Log("Sending data!..");
         if(!isServer && Network.isServer)
             GetComponent.<NetworkView>().RPC("SendPlayerData", NP, Vector3(data.positionX, data.positionY, data.positionZ), data.money, data.health, data.bulletsCur, data.bulletsClipCur, data.availableCars);
         else
             SendPlayerData(Vector3(data.positionX, data.positionY, data.positionZ), data.money, data.health, data.bulletsCur, data.bulletsClipCur, data.availableCars);
     }
     else{
         Debug.Log("file doesn't exist!");
         var bfN : BinaryFormatter = new BinaryFormatter();
         var fileN : FileStream = File.Create(Application.persistentDataPath + "/player_"+GUID+".dat");
         var dataN : playerData = new playerData();
         dataN.positionX = clientspawn.transform.position.x;
         dataN.positionY = clientspawn.transform.position.y;
         dataN.positionZ = clientspawn.transform.position.z;
         
         bfN.Serialize(fileN, dataN);
         fileN.Close();
         Debug.Log("Sending data!..");
         if(!isServer && Network.isServer)
             GetComponent.<NetworkView>().RPC("SendPlayerData", NP, Vector3(dataN.positionX, dataN.positionY, dataN.positionZ), dataN.money, dataN.health, dataN.bulletsCur, dataN.bulletsClipCur, dataN.availableCars);
         else
             SendPlayerData(Vector3(dataN.positionX, dataN.positionY, dataN.positionZ), dataN.money, dataN.health, dataN.bulletsCur, dataN.bulletsClipCur, dataN.availableCars);
     }
 }
 
 @RPC
 function SendPlayerData(positionS : Vector3, moneyS : int, healthS : int, bulletsCurS : int[], bulletsClipCurS : int[], availableCarsS : boolean[]){
     Debug.Log("Received player data!");
     myChar.transform.position = positionS;
     myChar.GetComponent(MoneySystem).money = moneyS;
     myChar.GetComponent(LifeSystem).health = healthS;
     myChar.GetComponent(Shooting).bulletsCur = bulletsCurS;
     myChar.GetComponent(Shooting).bulletsClipCur = bulletsClipCurS;
     myChar.GetComponent(CarSystem).availableCars = availableCarsS;
 }
 
 @RPC
 function SavePlayerData(GUID : String, positionS : Vector3, moneyS : int, healthS : int, bulletsCurS : int[], bulletsClipCurS : int[], availableCarsS : boolean[]){
     Debug.Log("Saving data: "+GUID);
     if(System.IO.File.Exists(Application.persistentDataPath + "/player_"+GUID+".dat")){
         Debug.Log("file exists!");
         var bf : BinaryFormatter = new BinaryFormatter();
         var file : FileStream = File.Create(Application.persistentDataPath + "/player_"+GUID+".dat");
         var data : playerData = new playerData();
         
         data.positionX = positionS.x;
         data.positionY = positionS.y;
         data.positionZ = positionS.z;
         data.money = moneyS;
         data.health = healthS;
         data.bulletsCur = bulletsCurS;
         data.bulletsClipCur = bulletsClipCurS;
         data.availableCars = availableCarsS;
         
         bf.Serialize(file, data);
         file.Close();
         
     }
     else{
         Debug.Log("file doesn't exist!");
         var bfN : BinaryFormatter = new BinaryFormatter();
         var fileN : FileStream = File.Open(Application.persistentDataPath + "/player_"+GUID+".dat", FileMode.Open);
         var dataN : playerData = new playerData();
         
         dataN.positionX = positionS.x;
         dataN.positionY = positionS.y;
         dataN.positionZ = positionS.z;
         dataN.money = moneyS;
         dataN.health = healthS;
         dataN.bulletsCur = bulletsCurS;
         dataN.bulletsClipCur = bulletsClipCurS;
         dataN.availableCars = availableCarsS;
         
         bfN.Serialize(fileN, dataN);
         fileN.Close();
     }
 }
 
 @RPC
 function RequestPlayerStatsData(){
     Debug.Log("Got ze rykvest");
     GetComponent.<NetworkView>().RPC("SavePlayerData", RPCMode.Server, playerGUID, myChar.transform.position, myChar.GetComponent(MoneySystem).money, myChar.GetComponent(LifeSystem).health, myChar.GetComponent(Shooting).bulletsCur, myChar.GetComponent(Shooting).bulletsClipCur, myChar.GetComponent(CarSystem).availableCars);
 }
 
 public class playerProfile{
     public var GUID : String = "";
     public var nickname : String = "";
 }
 
 public class playerData{
     public var positionX : float = 0;
     public var positionY : float = 0;
     public var positionZ : float = 0;
     public var money : int = 1000;
     public var health : int = 100;
     public var bulletsCur : int[] = [570, 90];
     public var bulletsClipCur : int[] = [30, 9];
     public var availableCars : boolean[] = new boolean[0];
 }
 
 public class serverData{
     public var propertyOwners : String[] = new String[1];
 }

screenshot-from-2015-03-15-112725.png (10.8 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by AurimasBlazulionis · Mar 15, 2015 at 10:26 AM

Fixed the code, by sending an rpc to everyone, adding network player inside parameters and everyone checks if it's their network player

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image WaxerPL · Jun 20, 2015 at 06:27 PM 0
Share

I've got the same problem with my code, can you send good code, I don't know what should be send to every one Request or Save and how to check network player

avatar image WaxerPL · Jun 23, 2015 at 05:45 PM 0
Share

PLease to answer me. It's wvery important ;)

avatar image
0

Answer by voncarp · Mar 15, 2015 at 10:25 AM

Your variables aren't matching up. Try debugging your data and dataN before you make the RPC call. Make sure your sending arrays for bulletsCurS, bulletsClipCurS, and availableCarsS.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AurimasBlazulionis · Mar 15, 2015 at 10:27 AM 0
Share

Just fixed everything, variables were all right

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Send model/GameObject from Server to Client 0 Answers

RPC return value 1 Answer

Very Strange RPC error 1 Answer

Acess server stuff by the client 0 Answers

Network Instiantiate Terrain (Voxel) issues C# 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges