0
\$\begingroup\$

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 );
}

enter image description here

I keep getting this error:

 get_transform  can only be called from the main thread.
 Constructors and field initializers will be executed from the loading thread when loading a scene.
 Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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 );
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Dec 7 '15 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.