Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Health Not Working Properly

Discussion in 'Multiplayer' started by UnityUser9860, Jan 28, 2017.

  1. UnityUser9860

    UnityUser9860

    Joined:
    Dec 8, 2015
    Posts:
    179
    Hello!

    I have a player that has a script attached called "HealthManager" wich contains the players health I want it so that each player has their own health and when they get low that player dies, I know how to add the dieing part but when the player gets damaged it only happens to the server how would I do what I want to do?

    Heres my script:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using UnityEngine.Networking;
    4. using System.Collections;
    5.  
    6. public class HealthManager : NetworkBehaviour
    7. {
    8.  
    9.     public const int maxHealth = 100;
    10.  
    11.     [SyncVar(hook = "OnChangeHealth")]
    12.     public int currentHealth = maxHealth;
    13.  
    14.     public RectTransform healthBar;
    15.  
    16.     public void TakeDamage(int amount)
    17.     {
    18.         if (!isServer)
    19.             return;
    20.  
    21.         currentHealth -= amount;
    22.         if (currentHealth <= 0)
    23.         {
    24.             currentHealth = 0;
    25.             Debug.Log("Dead!");
    26.         }
    27.     }
    28.  
    29.     void OnChangeHealth(int health)
    30.     {
    31.         //healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y);
    32.         GameObject.Find("Current_Health_Text").GetComponent<Text>().text = "Health: "+currentHealth.ToString();
    33.     }
    34. }
    Many thanks in advance!
     
  2. UnityUser9860

    UnityUser9860

    Joined:
    Dec 8, 2015
    Posts:
    179
    The thing thats attacking the player is the server
     
  3. SuperNeon

    SuperNeon

    Joined:
    Mar 16, 2014
    Posts:
    85
    Hi!

    You have to update the currentHealth value in the function OnChangeHealth :)
     
  4. UnityUser9860

    UnityUser9860

    Joined:
    Dec 8, 2015
    Posts:
    179
  5. UnityUser9860

    UnityUser9860

    Joined:
    Dec 8, 2015
    Posts:
    179
    SuperNeon likes this.
  6. SuperNeon

    SuperNeon

    Joined:
    Mar 16, 2014
    Posts:
    85
    hehe cool :)