-2

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();
Niklas
  • 955
  • 15
  • 29
Phillipv20
  • 58
  • 8

1 Answers1

0

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");
        return;
    }

    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!

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Not quite what I needed but I figured it out, I was calling the method PlayerHealth attached to PlayerController rather than locating the actual object which would be PlayerShip that had the script PlayerController on it. – Phillipv20 Sep 19 '16 at 02:46
  • Ok. How about the `OnAwake` function? That was correct? – Programmer Sep 19 '16 at 05:36