- Home /
Vector3 TransformDirection "object reference"-error
Hello!
Transform thisTransform;
Public Vector3 direction = Vector3.zero;
void Awake(){
thisTransform = GetComponent<Transform>();
direction = thisTransform.TransformDirection(Vector3.forward); //This line!
}
This is where I get the "Object reference not set to an instance of an object" error. The thing is, I have defined thisTransform as an object, so what more is there to "define"?
Any ideas?
Answer by whydoidoit · May 28, 2012 at 12:31 PM
You haven't put the character controller in the controller variable I'm guessing. The normal way to do this would be to use GetComponent:
void Start() {
controller = GetComponent(CharacterController);
}
Actually, I did, but forgot to include it in my sample -.- Hang on a $$anonymous$$ute, I'll edit my entire post.
Well you can just get the transform from "transform" no need for the GetComponent!
Actually it looks like you just want to do
direction = transform.forward;
No he want's to cache the transform so it'S ok. And yes, it doesn't matter if you use .transform or Getcomponent() it's the same. However the problem is that you shouldn't access other components in Awake. Awake is called immediately when the object is created. That means other components might not be there at this point.
For component cross references use Start() which is executed after all objects are created and initialized.
And finally this: thisTransform.TransformDirection(Vector3.forward);
equals this: thisTransform.forward;
Answer by Owen-Reynolds · May 28, 2012 at 06:19 PM
It's fine in Awake. I tried it exactly as written (well, the P in public should be lower-case.) The docs even say Awake is called after all objects are created (which I didn't realize -- thought it was called after each individually was created.)
But, yeah, the error is probably saying that thisTransform
is null. Try printing it to be sure. Is the script on some odd object that doesn't have a transform? (not sure how -- even empties have transforms.)
First, just a note: when @Bruflot posted this it was a different problem, which makes this whole thing look very confusing now :) For instance, there was not a Start or an Awake!
But to your point, I'm pretty sure that all Components are ready in Awake, but not any potential children due to an Instantiate of a connected set of objects. Is that your experience?
Your answer

Follow this Question
Related Questions
Velocity powered rigidbody on a moving platform without parenting. 3 Answers
NullReferenceException: Object reference not set to an instance of an object CannonFire.Update 0 Answers
Character Controller Respawn (Rotation Issue) 1 Answer
how can I make a character fly when holding down the jump button? 1 Answer
Restricting character controllers velocity after hitting a wall 1 Answer