# How can i fix “get_transform can only be called from the main thread” error in my code?

Here's my code:

var forward = transform.TransformDirection(Vector3.forward);
var input = Input.GetAxis("Vertical");
function Update(){
transform.position += forward * input * Time.deltaTime;
transform.Rotate( 0 , Input.GetAxis("Horizontal") * 45 * Time.deltaTime , 0 );
}


I keep getting this error:

 get_transform  can only be called from the main thread.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.


Don't referance GameObjects or Transforms (or components etc.) in initialization. Because Unity needs to prepare itself before you can access that objects to assign them to variables.

That is why we have an Awake() function, main purpose of Awake() function is field initialization before any Start() calls.

Like the error message tells you, the method you're using to assign a value to forward is being called in the loading thread because it's initializing the public field forward. It needs to be run during the game's main thread, so you need to move it.

function update() {
var forward = transform.TransformDirection(Vector3.forward);
var input = Input.GetAxis("Vertical");
transform.position += forward * input * Time.deltaTime;
transform.Rotate( 0 , Input.GetAxis("Horizontal") * 45 * Time.deltaTime , 0 );
}

• Start() would probably be a better place to move it to. It still gets called before Update(), but just once instead of every frame, more similar to the initializer OP is trying to replace. – DMGregory Dec 7 '15 at 13:14