Search Unity

Health Pick up - Null Reference Exception

Discussion in 'Scripting' started by LuDiChRiS000, Mar 10, 2018.

  1. LuDiChRiS000

    LuDiChRiS000

    Joined:
    Feb 19, 2018
    Posts:
    9
    Hi there, this should be pretty basic, but I just can't figure out what's going wrong. I have a HealthPick up with the following script on it. It references another script that is on the player called 'TankHealth.cs' the variable 'm_CurrentHealth' is public. When I enter the pickup collider I get:

    NullReferenceException: Object reference not set to an instance of an object
    HealthPickup.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/HealthPickup.cs:24)

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class HealthPickup : MonoBehaviour {

    public TankHealth tankHealth;
    public float healthBonus = 15f;

    void Awake()
    {
    tankHealth = FindObjectOfType<TankHealth> ();
    }

    void Update ()
    {
    transform.Rotate (new Vector3 (0, 90, 0) * Time.deltaTime);
    }

    void OnTriggerEnter(Collider other)
    {
    if (other.gameObject.tag == "Player")
    {
    Debug.Log ("Currnet Health: " + tankHealth.m_CurrentHealth);
    //Destroy (gameObject);
    //playerHealth.m_CurrentHealth = playerHealth.m_CurrentHealth + healthBonus;

    }
    }

    }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Try changing Awake to Start and also check that tankHealth != null, after your call to Find the object of type.
    Make sure it's working.
     
  3. LuDiChRiS000

    LuDiChRiS000

    Joined:
    Feb 19, 2018
    Posts:
    9
    Thanks, I added:

    void Start()
    {
    tankHealth = FindObjectOfType<TankHealth> ();
    if(tankHealth == null)
    {
    Debug.Log("cant found tank health");
    }
    }

    And sure enough, it is printing "cant found tank health" in the console... So that helps a bit, still not sure what the problem is though. The other script is definitely called 'TankHealth' :/
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Is the Tank definitely in the scene at the same time (or before) this pick up health script?
     
  5. LuDiChRiS000

    LuDiChRiS000

    Joined:
    Feb 19, 2018
    Posts:
    9
    Yes, the Players (there are 2 tanks on screen) are there in the scene the same time as the Health pick up. (I'm using the Unity TANKS! tutorial)
     
  6. LuDiChRiS000

    LuDiChRiS000

    Joined:
    Feb 19, 2018
    Posts:
    9
    Ah, you're correct! the Tanks, that have the TankHealth script on them are prefabs, that are spawned into the scene on play. Whereas the Health Pick up is just sitting in the scene hierarchy on play. I tested this by just placing a tank prefab in there too, and the error was gone. THANKS!
     
  7. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Cool no problem.