0
votes

I was learning multiplayer game implementation through Unity Multiplayer system. So I come across this really good tutorials written for beginners: Introduction to a Simple Multiplayer Example

From this tutorial, I can't able to understand this page content: Death and Respawning

Through this code, in tutorial they are talking about our player will respawn (player will transform at 0 position and health will be 100) and player can start fighting again.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;

public class Health : NetworkBehaviour {

public const int maxHealth = 100;

[SyncVar(hook = "OnChangeHealth")]
public int currentHealth = maxHealth;

public RectTransform healthBar;

public void TakeDamage(int amount)
{
    if (!isServer)
        return;

    currentHealth -= amount;
    if (currentHealth <= 0)
    {
        currentHealth = maxHealth;

        // called on the Server, but invoked on the Clients
        RpcRespawn();
    }
}

void OnChangeHealth (int currentHealth )
{
    healthBar.sizeDelta = new Vector2(currentHealth , healthBar.sizeDelta.y);
}

[ClientRpc]
void RpcRespawn()
{
    if (isLocalPlayer)
    {
        // move back to zero location
        transform.position = Vector3.zero;
    }
}
}

As per my thinking -> All clients are executing ClientRPC so all devices local players will move at the spawn position and health get full. As per this tutorial -> only own player's spawn position and health get updated.

So why this thing is happening that I can't able to understand? Actually RPC get called on all clients then all clients should require to move at start position and get full health. Please give me some explanation in this.

1

1 Answers

0
votes

As you can see on this image, you need to think that network systems aren't a "shared" room, they actually works as copying everything about the others on your own room. enter image description here Knowing that, now you can understand that if you send the Rpc from your Player 1, that Rpc will be executed on your Player1, and the Player 1- Copy on Player's 2 room.

Cause as you can read on the docs, the [ClientRpc] attribute:

is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on clients from a server.

So as Player 1 room is the host (server+client) an Player 2 is client, it will be executed on 2 room's, but evaluated on the first one.

Edit: That means that when, for example, Player 1 will die, it will call the RPC function, and (cause it's an RPC) his copy (Player1-Copy) on Room 2, will do the same.