Why Class Object is null?

Asked

Viewed 50 times

-4

I don’t understand why but the player object is null , I’m not calling it right ?

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;
            }

        }

    }
}
  • 1

    If you run Update before Start you will definitely be null.

  • And gameobject, you instance where?

1 answer

1

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

public HealthBar ()
{
    localScale = HealthTransform.localScale;
    PlayerObj = new Player();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.