-3

I am encountering a bug in a game I am trying to make. I am getting the following error.

NullReferenceException: Object reference not set to an instance of an object

This same code works fine in one of my other scripts but in this one it continues to through this error. I thought I set it to an instance of the object but I guess not.

UnityEngine.Component book001GUIOld = GameObject.FindWithTag("Book001Canvas").GetComponent("Canvas");
UnityEngine.Behaviour book001GUI = (UnityEngine.Behaviour)book001GUIOld;

Any Suggestions? Let me know if you need more of the code. I have also tried.

UnityEngine.Behaviour book001GUI = GameObject.FindWithTag("Book001Canvas").GetComponent("Canvas") as behaviour;
Jonah Starling
  • 539
  • 6
  • 20
  • 1
    just find out the bottom most stack which the object is null but it shouldnt be...NullReference is one of the easiest bug to debug.. – Steve Jan 24 '15 at 00:35

2 Answers2

0

Must be because GameObject.FindWithTag("Book001Canvas") returned null, then .GetComponent("Canvas"); throws a exception.

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Ecnerwal
  • 362
  • 1
  • 2
  • 15
0

From the GameObject.FindWithTag documentation:

Description

Returns one active GameObject tagged tag. Returns null if no GameObject was found.

So you might want to try to catch the error:

var book001Canvas = GameObject.FindWithTag("Book001Canvas");

if (book001Canvass != null)
{
    UnityEngine.Component book001GUIOld = book001Canvas.GetComponent("Canvas");
}
else
{
    // Recover from not finding an object with the Book001Canvas tag
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43