- Home /
How to pass values between networked players?
I have a game set up with three players connected using MasterServer
, but now I want to access values from other players, for example, I want each player to be a different character, so I want to limit each player's choice based on other players' choices.
My initial thought was seeing if there is a way to access static variables by doing something like Network.Connections[0].character
but there doesn't seem to be a way to do that.
Another idea was to create a game object with a name that matches that character's name whenever a player chooses a character so I could use GameObject.Find
to see if that object exists and therefore has been selected, but that seems like a hacky way to do it.
Lastly I've looked into Remote Procedure Calls, but I haven't got my head round that yet. if that's the way to go, I can update this or ask a new question with more details.
Answer by whydoidoit · Feb 10, 2014 at 01:24 PM
When you create you prefab for the character have it register itself in a list of the current characters.
using System.Collections.Generic;
using System.Linq;
...
public static List<Player> players = new List<Player>();
void Awake() {
players.Add(this);
}
void OnDestroy() {
players.Remove(this);
}
Then you need to RPC when a player selects a name
public string name;
bool NameSelected(string newName) {
if(players.Any(p=>p.name == newName)) {
return false; //Name not available
}
networkView.RPC("SetName", RPCMode.All, newName);
return true;
}
[RPC]
void SetName(string newName) {
name = newName;
}
This process is happening in the lobby before the game, so I don't need to create the characters yet. Using your suggested method, creating a list of strings with the characters' names and checking it to see if that player exists should be good, but now I just need to add a string to the list via RPC.
Yep that sounds good to me. Just have a single object in the lobby that maintains the list and have it shared between players (an object with a network view that exists in the scene).
Not sure how to do that, and wouldn't that stop it working when you load a new scene?
It's just there to set the names in the lobby right? Just to de-dupe them. I guess you'd give the player the actual name so it wouldn't matter that it wasn't there in the next scene. But it should also work fine if you make it "DontDestroyOnLoad"
Yeah that's true it doesn't actually matter, I'm just over-thinking it. In your example the RPC updates the local name variable, but I'm not sure why and ins$$anonymous$$d I update the list of players to get it to work. I then also buffer the RPCs to make sure late joiners can't choose selected players.
Your answer
Follow this Question
Related Questions
Port forwarding 1 Answer
Creating servers properly? 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Port not opening? 3 Answers