Networking

Unity Logo

Are we recording?

Meow Cam

Network architectures

peer2peer vs clientserver

MLAPI

mlapi logo

Install networking library

  1. Install git
  2. Window -> Unity package manager
  3. + -> Add package from git URL
  4. Enter the following:
    com.unity.multiplayer.mlapi
  5. Click Add

NetworkManager

  • There must be only 1 NetworkManager(Singleton pattern)
  • Handles networking settings and connections
  • Can spawn a prefab(PlayerObject) for every connected player
  • Contains a list of all spawnable prefabs
  • Every player may own 1 PlayerObject and many NetworkObjects

NetworkObject

  • It is required if the object has networking functionality
  • Replicates the object in every instance of the game
  • Allows association of the object across instances by assigning it a NetworkId
  • Every NetworkObject has an owner
  • Must be added only once either in the object or in a parent object

Network Transform

  • Syncs the position and rotation of gameobject of the owner to all other clients
  • Doesn't work sync scaling

NetworkNavMeshAgent

  • Shares movement when using navmeshes
  • Only the owner should change NavMeshAgent
  • Changed settings at runtime aren't synced so you should use RPCs

NetworkAnimator

  • Syncs animations accross network
  • You must attach an animator component to it
  • Only the owner of the gameobject should update the state of the animator
  • Doesn't work with triggers, you should do that manually with RPCs

Spawning GameObjects

Instantiate creates gameobject localy. Spawning creates it in the other clients as well. Only the server can destroy or despawn.

GameObject go = Instantiate(myPrefab, Vector3.zero, Quaternion.identity);
go.GetComponent<NetworkObject>().Spawn();

What is RPC?

  • A function call which is executed in another program or computer
  • It looks like a normal function call
  • Must have [ServerRpc] or [ClientRpc] attribute
  • RPCs have optional parameters like if you want a ClientRpc to be sent to one or all clients

RPC

rpc image

NetworkBehaviour

  • Used to create your custom netowrking scripts
  • Can contain RPCs and network variables
  • Is owned by the NetworkObject

NetworkVariable

  • Variables shared accross network
  • You can setup read and write permissions for the clients and the server
  • You can create your own types by implementing INetworkVariable

Using network variables


NetworkVariable var = new NetworkVariable(permissions);
//access value 
var.Value = newValue;
//setup subscribers
private void OnEnable(){
	var.OnValueChanged += subscribedCallback;
}
private void OnEnable()
{
	var.OnValueChanged -= subscribedCallback;
}

				

Changing scenes

The server can change the current scene with NetworkSceneManager

//This can only be called on the server
NetworkSceneManager.SwitchScene(mySceneName);

Useful Links

  • MLAPI documentation
  • Questions?

    Question Cat