All health in one script


Because the same health script is used on both the player and the enemy, a simply way to avoid having to use multiple scripts is to just use a public variable to get the enemy target.

So on my player, I have a public variable for the combat target (we already put the combat target script on the enemies)

so in the HealthDisplay script, I simply look at that public variable. (FYI: I am using some state machines, so you may see some references to that, but the principle is the same)

On my Player (or in your playercontroller script), I have a public variable for the combat target (a public getter and a private setter to prevent anything outside of the script changing the target):

public CombatTarget combatTarget { get; private set; }

Then in my healthdisplay script, I simply reference the Player and get the info from the player’s combat target and then display the health. If the target dies the display goes back to showing Nothing for the enemy, but if you switch targets, it changes to that targets health percent

healthdisplay script:

private const string PLAYER = "Player";

        [SerializeField] private TMP_Text playerHealthPercent;
        [SerializeField] private TMP_Text enemyHealthPercent;

        private GameObject player;
        private Health playerHealth;
        private Health enemyHealth;

        private void Awake()
            player = GameObject.FindGameObjectWithTag(PLAYER);
            playerHealth = GameObject.FindWithTag(PLAYER).GetComponent<Health>();

        private void Update()
            // String.Format 0:0  - first value, 0 decimal spots.   0:0.0  first value, 1 decimal spot
            playerHealthPercent.text = String.Format("{0:0.0}%", playerHealth.GetHealthPercent());

            // return if there is no enemy targeted
            if (player.GetComponent<PlayerStateMachine>().combatTarget == null) 
                enemyHealthPercent.text = "";

            enemyHealthPercent.text = String.Format("{0:0.0}%", enemyHealth.GetHealthPercent());

        private void EnemyTargeted()
            enemyHealth = player.GetComponent<PlayerStateMachine>().combatTarget.GetComponent<Health>();

Privacy & Terms