How Do I call a variable of another class ?

script 1

public class player_a : MonoBehaviour {
    public float  life;
}

script 2

public class player_b : MonoBehaviour {
    public int Damage;

    void Update () {
    life = life - Damage
        }

If the scripts are attatched the the same gameobject, you can do

gameObject.GetComponent<player_a>().life -= damage;

but, it looks like you’re doing two seperate players, so i would advise doing 1 player first with all needed Variables & functions, then work on dealing damage ect.

EDIT: All variables must be public, if you wish to inherit them in other scripts

1 Like

thank you :slight_smile:

Don’t make the variables public. Make them private and set up Getters and Setters to access them. it’s just “good practice”. I’m assuming most Unity programmers adhere to these common practices, even though some things seem different over here :slight_smile:

So something like

    // the private variable for the class
    private int life;

    // public getter and setter for other classes to use
    public int Life 
    {
        get 
        {
            return this.life;
        }
        set 
        {
         // include any checks you want to take place in here before setting the value
            life = value;
        }
    }
1 Like