0

I'm working on an adventure game in Unity 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 that is attached to prefab2 works just fine.

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

I've tried finding a solution for the last 4 hours, but to no avail. Any help would be appreciated.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217

1 Answers1

1

I found the solution, the game object was being stored as a transform, rather than a game object. This had me confused because of a similar script I was running that also used a transform (Which worked just fine).

  • The 'as' command will try to cast it to the given type. if its not castable you get null as result. if you cast it with (targettype)objectreference you will get an exception if the type is not castable – Florian Schmidinger Jan 16 '15 at 08:19