Hook = name of in HealthUI lesson

Hi,

In the HealthUI lesson of the Unity Multiplayer course, I have the HandleHealthUpdate method that gets called by the SyncVar with the hook that assign the currenthealth variable value to the newHealth parameter of the HandleHealthUpdate

public class Health : NetworkBehaviour
{
   [SerializeField] int maxHealth = 100;

   public event Action serverOnDie;

   public event Action<int, int> ClientOnHealthChange;

   [SyncVar (hook = nameof(HandleHealthUpdate))]
   int currentHealth;

#region  Server
    public override void OnStartServer()
    {
        currentHealth = maxHealth;
    }

    public void DealDamage(int damageAmount)
    {
        if(currentHealth == 0) { return;}

        currentHealth = Mathf.Max(currentHealth - damageAmount, 0);

        if(currentHealth != 0 ) {return;}

         serverOnDie?.Invoke();

         Debug.Log("we died");   
    }

    #endregion

    #region Client
     
     void HandleHealthUpdate(int oldHealth, int newHealth)
     {
        ClientOnHealthChange?.Invoke(newHealth, maxHealth);
     }

    #endregion
}

The script works, but my question is how the SyncVar knows to which of the two method parameters it has to assign the currenthealth value? There is no part in the class where we specifically ask the SyncVar to hook the currenthealth value to the newHealth parameter.

Thank you for the help.

This is built into the framework. When the value changes, the framework will call your hook and put the correct values into the correct parameters

Hi Bixarrio,

Thank you for the answer, will the correct parameter always be the second one? Or is there some other logic behind it? I tried check the mirror documentation here : SyncVar Hooks - Mirror but it does not mention anything about it. This is purely a curiosity.

I believe so. Afaik the signature of the hook should always be name(old value, new value)


Edit
I just checked the docs you linked and I am correct;

It doesn’t explicitly say the second is the new value but it is, and it will always be. It will be quite a nightmare to develop anything if you don’t know which parameter holds which value

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms