on triggerStay2D can't modify variable on collider object

Hi all Can’t make this trigger to work i don’t get any error from unity and the debug log works fine but the assignment of the new value to the player stats script doesn’t work and can’0t understand why any idea ? thank you for your help

using UnityEngine;
using System.Collections;

public class FireDamage : MonoBehaviour {

	void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            float health = other.gameObject.GetComponent<PlayerStats>().health;
            Debug.Log(health.ToString());
            health = health - 1;
            
        }
    }
}

Try replacing:

float health = other.gameObject.GetComponent<PlayerStats>().health;
Debug.Log(health.ToString());
health = health - 1;

with:

other.gameObject.GetComponent<PlayerStats>().health -= 1;

What you are doing is the following:

you have a variable in the class PlayerStats called health. You get the value of that variable (for example 5) and create a new variable called health inside your class. That new health, gets the value of the player’s health. So you have a PlayerStats.health == 5 and a FireDamage.health == 5.

You then change your LOCAL health variable (the FireDamage.health) to 4 (5-1). This does not affect the original health, because your variable is NOT A REFERENCE to that other variable. This is because floats are value types and not reference types. This means that when you write float x = float y, it means that x will have the value of y but changes to one will not affect the other, as THEY DO NOT REFER TO THE SAME DATA.

In order to have a reference to the data of your player, you need a reference type. Such types are classes and their instances. This means that you should do the following:

if (other != null && other.CompareTag("Player")))
{
PlayerStats playerStatistics = other.gameObject.GetComponent<PlayerStats>();
playerStatistics.health = playerStatistics.health -1;
}

This way, you get a reference to your player’s stats. Every data included in playerStatistics is not an actual variable, just a reference to the player’s stats, so everything that you do to them is affecting the referenced variables.