Object reference not set to an instance of an object.

I’m working on an adventure game and ran into this little bug. I’m trying to access a script within an instantiated object. Here is the related line of code:

    public void CastAbility(Vector3 targetLocation) {
        print (targetLocation);
        var target = Instantiate (prefab2, transform.position, transform.rotation) as GameObject;
        Initialize initialize = target.GetComponent<Initialize> ();
        initialize.targetLocation = targetLocation;
    }

From my understanding, the first line of code will create a Game Object called prefab2.
The second line of code will allow me to access the component (A script) within prefab2.
The third line will alter a variable within prefab2’s script.

It seems logical to me, however I am getting a
“Object reference not set to an instance of an object” error.

Here are some details, if this helps find a solution.

  1. If I just use Instantiate, and leave out the target.GetComponent, the prefab2 will spawn and will not give me any errors… In fact the Initialize script works just fine.

  2. I am calling the CastAbility function from an instantiated child object.

Any help would be appreciated.

Be sure to check the unity documentation before posting here. You’ll get your answers faster!

It’s either unable to instantiate the prefab, or it’s unable to find the initialize script. Depends on which line is throwing the error. Ensure that prefab2 points toward an actual prefab gameobject that also has the Initialize script on it.

I’ve been reading documentation all day haha :slight_smile:
I did check numerous times to verify that the prefab2 did exist, and that it contains the Initialize script. Here are two images to show it, am I missing something?

This shows that prefab2 contains the Initialize script.
http://tinypic.com/view.php?pic=2py44s7&s=8#.VLjBrivF_To

This shows that the player object has the prefab2 correctly placed in it.
http://tinypic.com/view.php?pic=11johee&s=8#.VLjB5yvF_To

In the second image you’ll notice that prefab 2’s assigned type is a Transform. Make sure prefab 2 is set to type “GameObject” in your cast Script.

What instantiate is trying to do the way you’ve made it is make a copy of only the prefabs transform component, and then trying to cast the result of that to to a GameObject, which results in null.

1 Like

Thanks for the help BenZed! Without you I would have never noticed the problem. I will do my part now and answer any questions on the forums that I know how to answer.

Its amazing how such a simple problem can cost me so much time :stuck_out_tongue:

1 Like

Haha, oh man. I’ve been there.