- Home /
Rpc cannot change variable in function OnConnectedToServer!
Hi
I try to make a game where 3 players connect to a server, and the server can play along, i wanna define each player as a NetworkPlayer by counting numbers of connections. I syncronize with RPC call which works just fine to change the count variable at both server and clients. BUT when i try to call the variable in the OnConnectedToServer() function, it suddenly do not work, here is a short version of my code. Thanks in advance.
static var connected : int = 0;
var connected_S : int = 0;
static var server : NetworkPlayer;
static var player2 : NetworkPlayer;
static var player3 : NetworkPlayer;
static var player4 : NetworkPlayer;
function OnGUI()
{
if(Network.isServer)
{
if(Start_Game)
{
networkView.RPC ("Conections", RPCMode.All, connected_S);
}
}
}
function OnPlayerConnected(player: NetworkPlayer)
{
connected_S += 1;
print(connected);
}
function OnConnectedToServer()
{
print(connected);
if(connected == 0)
{
player2 = Network.player;
}
if(connected == 1)
{
player3 = Network.player;
}
if(connected == 2)
{
player4 = Network.player;
}
}
@RPC
function Conections(connection : int)
{
connected = connection;
print (connected);
}
Hi, thanks for your answer, 'connected_S' is a local variable the server uses to set the global variable 'connected' which will be used in the OnConnectedToServer() to define how many players that is connected at the current time.
Your code is not optimized and very confusing.
First of all, you should not be calling an RPC function in an OnGUI call since you'll be wasting a lot of cycles sending redundant work across the network.
Secondly, assu$$anonymous$$g that no external script would be accessing those particular variables in your script -- and there's no reason for them to do so, as far as I can tell -- then you don't have to declare them static. That might confuse you into thinking that the NetworkView automatically synchronizes them across the network.
And lastly, there is no need to declare those variables in the first place. You can always check the number of connections in the server and all of the clients' information by accessing Network.connections from the server-side script. You don't have to manually store those data in your own variables per connection. And because you can access all that data in one call, you can simply send that just before the game starts, i.e., you don't need to send it across the network piecewise.
Optimize your code a little bit based on those points and you might find your glitch somewhat nonexistent.