Retrieving RectTransfrom from null reference possible???

I stumbled across a very strange behaviour. I received a reference to a RectTransform of an uninstantiated and therefore null gameobject.
I wanted to read the extends from a child RectTransform of a prefab without instantiation. The following code did that:

	public static Vector2 GenerateMeasureForMessage (ES_Message message){

		RectTransform messageRect = message.transform.GetChild (0).GetComponent<RectTransform> ();
		return messageRect.offsetMin - messageRect.offsetMax;
}

the following screenshot shows, that, since I use the “message” prefab directly, all its MonoBehaviour variables are still null.

The next screenshot however shows, that it was still possible for the code or Unity or… to retreive the reference

I stumbles across this, because I moved the code into another static variable, doing the exact same stuff, just relaying the work to another static method and THERE it threw the NullReferenceException.

The weird stuff does not happen in the class that holds the prefabs, it’s already a different class.

I don’t get how this works.

Ahh thanks @tanoshimi, I didn't know you could use the string version of the character.

1 Answer

1

I think “uninstantiated and therefore null” is the problem. AFAIK, uninstantiated prefabs are real gameObjects, which just aren’t in the scene (and never will be.) You can examine them like anything else. As NoseK writes, the debugger looks to be wrong.

I remember it was even common to change parts of a prefab by mistake, with no harm done. Many Qs asked why a=Instantiate(b); b.thisAndThat=wasn’t changing their scene object a. No errors – just nothing happened. And I can print transform.position directly from my prefabs.

Sure, it’s a get, and not a variable, but I think the debugger calls it like normal – any funny unpacking prefab stuff should work either way. Maybe it’s not fully set-up(?) (but then why would it work in picture #2?) Maybe there’s also an issue specific to RectTransforms. Maybe.

Thanks Owen for the rundown. I remember the same thing about changing prefab variables from code. It's just weird, that running the code works, but putting it into yet another static method works different and throws the exception. Maybe I get to understand that at some point, but for now I think your answer suffices

Ah ... I didn't even notice the part about it working one way, but not the other. AFAIK, running something through a static method or a member function shouldn't matter (I think you can't start a coroutine from a static, but you're not doing that, are you?) My guess is that one version just happened to be called before the message argument was created. If you can get it to work/notWork simply by changing a function to static and back, that would be a real mystery.