I tried to make a simple miltiplayer game with the unity tutorial. The Code of the Player looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerController : NetworkBehaviour {
public GameObject bulletPrefab;
public Transform bulletSpawn;
public Camera cam;
// Update is called once per frame
void Update () {
if (!isLocalPlayer) {
return;
}
float x = Input.GetAxis ("Horizontal") * Time.deltaTime * 150.0f;
float z = Input.GetAxis ("Vertical") * Time.deltaTime * 3.0f;
transform.Rotate (0, x, 0);
transform.Translate (0, 0, z);
if(Input.GetKeyDown(KeyCode.Space)){
CmdFire();
}
}
void Start()
{
cam.gameObject.SetActive(false);
if(isLocalPlayer)
{
cam.gameObject.SetActive(true);
}
}
[Command]
public void CmdFire(){
GameObject bullet = (GameObject)Instantiate (bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 6.0f;
// Spawn the bullet on the client
NetworkServer.Spawn(bullet);
Destroy (bullet, 2f);
}
public override void OnStartLocalPlayer ()
{
GetComponent<MeshRenderer> ().material.color = Color.blue;
}
}
The Code of the health class like this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Health : NetworkBehaviour {
public const int maxHeath = 100;
[SyncVar(hook="OnChangeHealth")] public int currentHealth = maxHeath;
public RectTransform healthBar;
public RectTransform publicHealthBar;
private int maxHealthBarSize;
public bool destroyOnDeath;
private NetworkStartPosition[] spawnPoints;
void Start(){
if (isLocalPlayer) {
spawnPoints = FindObjectsOfType <NetworkStartPosition>();
maxHealthBarSize = (int) healthBar.sizeDelta.x;
}
}
public void TakeDamage(int amount){
if (!isServer) {
return;
}
currentHealth -= amount;
if (currentHealth <= 0) {
if (destroyOnDeath) {
Destroy (gameObject);
}
else {
currentHealth = maxHeath;
RpcRespawn ();
}
}
}
void OnChangeHealth(int health){
if(isLocalPlayer)
{
healthBar.sizeDelta = new Vector2(((float)health / maxHeath) * maxHealthBarSize, healthBar.sizeDelta.y);
}
}
[ClientRpc]
void RpcRespawn(){
if (isLocalPlayer) {
Vector3 spawnPoint = Vector3.zero;
if (spawnPoints != null && spawnPoints.Length > 0) {
spawnPoint = spawnPoints [ Random.Range (0, spawnPoints.Length) ].transform.position;
}
transform.position = spawnPoint;
}
}
}
But the health bar is only updating on 1 client. This means : A shoots B -> B's Healthbar updates -> B shoots A -> A's healthbar doesn't update.Does anyone know howw to fix the issue? (Is it unity or me?) Probably me :)