Phillipv20 Phillipv20 - 1 year ago 93
C# Question

Why am i Getting NullReferenceException when trying to create a HealthPack in Unity C#?

Ok guys and gals I'm having an issue again with some code. Basically once I start and it attempts to create a Health Pack it's throwing an error that:

NullReferenceException: Object reference not set to an instance of an object
HealthSpawnerScript.Update () (at Assets/Scripts/HealthSpawnerScript.cs:31)

below is the code i'm running. The gameobject PlayerController houses a method used to return Player Health named PlayerHealth(). In awake I set playerController to find the script and method I'm after. Then in update i'm trying to call the method and assign it to a variable for use in the script later. I know this should be simple but i'm having a brain fart guys.

public PlayerController playerController;
private int healthHolder;

void OnAwake()
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();

// Use this for initialization
void Start ()
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;

//playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();

// Update is called once per frame
void Update ()
healthHolder = playerController.PlayerHealth();

Answer Source

There is no Unity callback function named OnAwake. You are likely looking for the Awake function.

If that is fixed and your problem is still there, you have to seperate your code into pieces and find out what's failing.

playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();

should be changed to

void Awake()
    GameObject obj = GameObject.Find("PlayerHealth");
    if (obj == null)
        Debug.Log("Failed to find PlayerHealth GameObject");

    playerController = obj.GetComponent<PlayerController>();
    if (playerController == null)
        Debug.Log("No PlayerController script is attached to obj");

So, if GameObject.Find("PlayerHealth") fails, that means there is no GameObject with that name in the scene. Please check the spellings.

If obj.GetComponent<PlayerController>(); fails, there is no script called PlayerController that is attached to the PlayerHealth GameObject. Simplify your problem!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download