Why class object is null?

-4

I do not understand why but the player object is null, am I not calling it well?

public class HealthBar : MonoBehaviour {

    Vector3 localScale;
    public Transform HealthTransform;
    public Player PlayerObj;

    void Start () {

        localScale = HealthTransform.localScale;
        PlayerObj = new Player(); 
    }

    void Update () {



        if(PlayerObj.GetPlayerAxis().Equals("P1Horizontal"))
        {
            localScale.x = Player.HealthAmountP1;
            if (gameObject.name.Equals("P1Health"))
            {
                HealthTransform.localScale = localScale;
            }
        }
        if (PlayerObj.GetPlayerAxis().Equals("P2Horizontal"))
        {
            localScale.x = Player.HealthAmountP2;

            if(gameObject.name.Equals("P2Health"))
            {
                HealthTransform.localScale = localScale;
            }

        }

    }
}
    
asked by anonymous 16.07.2018 / 17:31

1 answer

1

The Player object is initialized only in the Start method which means that you must call the Start method in your code before any call of the Update method. One solution to avoid this would be to add a constructor to your class by initializing the variable Player .

public HealthBar ()
{
    localScale = HealthTransform.localScale;
    PlayerObj = new Player();
}
    
17.07.2018 / 15:36