Unity nulling variables for instantiated GameObject?

Unity appears to be clearing the variable for an instantiated GameObject as it’s created, for no reason I can figure out.

I’ve basically just got a simple:

GameObject newObj = Instantiate(theObj, thePos, rotation) as GameObject;
otherVar = newObj.GetComponent<script >();

But I’m getting a NullReferenceException for newObj – running a Debug.Log on it shows me that it’s null, even though the gameobject was created.

This is really driving me insane, because this exact code worked for 2 weeks and now it’s suddenly breaking. I’ve also tried declaring the variable up top and then using it, but no dice. What’s going on??

Are you sure that “theObj” is of type “GameObject”? If it’s something else the as-cast will return null when the returned type can’t be casted into a GameObject.

If you don’t explicitly want to get null if the cast fails you should use a normal cast:

GameObject newObj = (GameObject)Instantiate(theObj, thePos, rotation);

In this case the runtime will throw an excetion if the cast fails. You should always use this cast since it makes it easier to spot the error.