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.

3
  • 1
    What is a NullReferenceException and how do I fix it? Commented Jan 16, 2015 at 7:38
  • what happens if you cast it like this: 'var target = (GameObject)Instanciate(ommited parameters)'? If it throws invalid cast exeption you are at the bottom of the problem Commented Jan 16, 2015 at 7:39
  • is initialize null or is target null? Commented Jan 16, 2015 at 7:45

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.