Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Object Reference Set To Null

Discussion in 'Scripting' started by ansonisawesome24, Mar 21, 2020.

  1. ansonisawesome24

    ansonisawesome24

    Joined:
    Dec 23, 2019
    Posts:
    13
    I keep getting the error: upload_2020-3-20_19-10-45.png
    This is my health script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. public class Health : MonoBehaviour
    6. {
    7.     int health;
    8.     int healthMax;
    9.  
    10.     public Image healthBar;
    11.  
    12.     public Health(int healthMax)
    13.     {
    14.         this.healthMax = healthMax;
    15.         health = healthMax;
    16.     }
    17.  
    18.     public int GetHealth()
    19.     {
    20.         return health;
    21.     }
    22.  
    23.     public void Damage(int damageTaken)
    24.     {
    25.         health -= damageTaken;
    26.         healthBar.fillAmount -= damageTaken/100f;
    27.  
    28.         if (health < 0)
    29.         {
    30.             health = 0;
    31.         }
    32.     }
    33.  
    34.     public void Heal(int healAmount)
    35.     {
    36.         health += healAmount;
    37.         healthBar.fillAmount -= healAmount / 100f;
    38.  
    39.         if (health > healthMax)
    40.         {
    41.             health = healthMax;
    42.         }
    43.     }
    44. }
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,890
    You can't use constructors with MonoBehaviours. It's instanced when added to a GameObject via click-drag or by using
    go.AddComponent<Health>()
    .
     
  3. ansonisawesome24

    ansonisawesome24

    Joined:
    Dec 23, 2019
    Posts:
    13
    Sorry, I am new, what should i do?
     
  4. ansonisawesome24

    ansonisawesome24

    Joined:
    Dec 23, 2019
    Posts:
    13
    Never mind, I figured it out