0

so...my issue is at healthText.text = "health: " + Health my console says object reference is not set to an instance of the object. Sorry for the terrible code but i'm into coding for only 2.5 weeks so, don't stick your eyes out pls.

using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    using UnityEngine.UI;
    public class PlayerDED : MonoBehaviour
    {
        public int Health = 100;
        public int damage = 2;
        public Text healthText;
        public bool AlreadyTook = false;
        // Start is called before the first frame update

        void Update(){
            Die();
            healthText.text = "Health : " + Health.ToString();
            }
       void TakeDamage(){
           Health -= damage;
       }
       public void Die(){
           if(Health <= 0){
                Debug.Log("SceneManager.LoadScene(Dead);)");
           }
       }
       void OnCollisionEnter2D(Collision2D col ){
           if(col.collider.tag == "Enemy" && AlreadyTook == false){
               AlreadyTook = true;
               TakeDamage();
           }
       }
       void OnCollisionExit2D(Collision2D col){
           if(col.collider.tag == "Enemy"){
               AlreadyTook = false;
           }
       }










       }

1 Answers1

0

You've declared public Text healthText; at the top, but you've never initialized it with anything so when you try to assign the text property a value you get the object reference error. It's like asking about someone's friend, but never specifying that someone.

Try initializing healthText with an instance of Text. I'm not familiar with the type, but it might just be like this: healthText = new Text().

The Muffin Man
  • 19,585
  • 30
  • 119
  • 191
  • i'm not quite sure what you mean by that, i'm working in unity, so i declared the text which i will need to put in the editor.I also did it exactly the same with my scoreboard and it doesn't give any error at all, which confuses me even more – Infinity Animations Mar 02 '20 at 21:09
  • First and foremost, set a break point and run the game in debug mode so that you can step through the code. You can use your mouse cursor on the variable names to see which one isn't initialized. Maybe you removed the text in the editor and it left behind that code fragment? Who knows. – The Muffin Man Mar 02 '20 at 21:18