Repository navigation
Networking
André edited this page Jul 13, 2022
·
3 revisions
The networking exists in every script and GameObject in our game. It's the main component of how everything works and all it does is manage the messages sent and received by the players.
To send a message to the server any client can call a function with the ServerRPC Attribute.
[ServerRPC]
public void SendAMessageServerRPC(ParamType paramName)
{
// Because of a bug in the Networking API we need to check if the receiver is the server or not. If it's not the server, then do nothing.
if(!IsServer) return;
// This will print the message "Hello World!" in the Server Console.
Debug.Log("Hello World!");
}To send a message to a client or all the clients the server can call a function with the ClientRPC Attribute. The only difference is that if the function is contained in the Player class, you'll have to call the function through the player
// Basic Remote Procedural Call
[ClientRPC]
public void SendAMessageClientRPC(ParamType paramName)
{
Debug.Log("Hello World!");
}
// In case you want to send it to a specific client.
private void SomeFunction()
{
...
client.SendAMessageClientRPC();
...
}
// In case you want to send it to every client.
private void SomeFunction()
{
...
SendAMessageClientRPC();
...
}You can have Network Variables that are self-managed. This is useful in cases where you want everyone to know a certain value, like a certain player's Health Value, for instance.
public class ClassName : NetworkBehaviour
{
// You can specify in the constructor wether you want the variable to be readable by everyone or a group of people, or accessed by everyone or a group of people.
public NetworkVariable<Type> variableName = new();
// You can also register a function to its OnChanged event like this
public void FunctionName()
{
...
variableName.OnChanged.AddListener(nameof(FunctionYouWantToRegister));
...
}
}```Getting Started