Enemy Health doesnt sync when player enter room later

I have some difficulty on multiplayer photon 2. when the first player enters the room, the first player and enemy were there. when the player collides with the enemy, the enemy health decrease by 10. when another player enters the room later, the enemy health reset to 100 in second player's view. It needs the later player collides with the enemy to sync the health with the masterclient.

Here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;

public class SharkHealth : MonoBehaviourPunCallbacks, IPunObservable
{
public GameObject[] fishCollision;
public GameObject shark;

[Header("Health Related Stuff")]
public float startHealth = 100;
private static float health;
[SerializeField]
Image healthbar;

void Start()
{
health = startHealth;
healthbar.fillAmount = health / startHealth;
die = GetComponent<Animator>();

for (int i = 0; i < 29; i++)
{
fishCollision = GameObject.FindWithTag("fish");
Physics.IgnoreCollision(fishCollision.GetComponent<BoxCollider>(), GetComponent<CapsuleCollider>());
}
}

//sync health
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
// We own this player: send the others our data
stream.SendNext(health);
}
else
{
// Network player, receive data
health = (float)stream.ReceiveNext();
}
}

private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag.Equals("fish"))
{
gameObject.GetComponent<PhotonView>().RPC("TakeDamage", RpcTarget.AllBufferedViaServer, 10f);
}
}

[PunRPC]
public void TakeDamage(float damage)
{
health -= damage;
Debug.Log(health);

healthbar.fillAmount = health / startHealth;

if (health <= 0f)
{
//die
Dead();
}
}

void Dead()
{
if(photonView.IsMine)
{
shark.SetActive(false);
//StartCoroutine(Respawn());
}
}
}

Comments

  • First at all, don't use
    RpcTarget.AllBufferedViaServer
    
    when it is not necessary. You are synchronizing HP in
    OnPhotonSerializeView
    
    and this is enough to have synchronized hp values after a new player joins.

  • I used
    RpcTarget.All
    
    after reading your comment. when I testing the project, the player who enters later still can see the half health of mainclient's full. the health only syncs when the player collides with the mainclient :(
  • qilS wrote: »
    I used
    RpcTarget.All
    
    after reading your comment. when I testing the project, the player who enters later still can see the half health of mainclient's full. the health only syncs when the player collides with the mainclient :(

    should I change the start to update?
  • Is
    SharkHealth
    
    component attached to Observed Components in PhotonView?
  • yes it is. anyway thank you :))
  • anyway i got the solution ady. thank you. i put the
    healthbar.fillAmount = health / startHealth;
    
    in update also.