Movement Script Error

Hey people, I tried to create a Simple Movementscript and it worked but as soon as i moved the checks out of FixedUpdate and moved them to their respective booleans my code broken and i don’t know why. Help would be appreciated.
Error: "
UnityException: GetKeyString is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour ‘PlayerMovement’ on game object ‘Player’.
See “Script Serialization” page in the Unity Manual for further details."
I checked The page in the Manual and i didn’t find anything useful.
Code:

/* using System.Collections;
using System.Collections.Generic; */
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public float Xforce = 750f;
    public float Yforce = 750f;
    public float Zforce = 750f;

    static bool Z;
    static bool NegX;
    static bool NegZ;
    static bool X;

    public Rigidbody rb;
    // Start is called before the first frame update
    void Start() {
        Debug.Log("Initializing PlayerMovement");
    }
    // Update is called once per frame
    void Update() {
        if(Input.GetKey("w")) {
            Z = true;
        }/*else if(NegX == true) {
            rb.AddForce(-Xforce * Time.deltaTime, 0, 0);
        }else if(NegZ == true) {
            rb.AddForce(0, 0, -Zforce * Time.deltaTime);
        }else if(X == true) {
            rb.AddForce(Xforce * Time.deltaTime, 0, 0);
        }*/

       /*Z == Input.GetKey("w");
       NegX == Input.GetKey("a");
       NegZ == Input.GetKey("s");
       X == Input.GetKey("d");
       */
    }
    // FixedUpdate is called once per frame (Physics Calculation)
    void FixedUpdate() {


        if(Z == true) {
            rb.AddForce(0, 0, Zforce * Time.deltaTime);
        }else if(NegX == true) {
            rb.AddForce(-Xforce * Time.deltaTime, 0, 0);
        }else if(NegZ == true) {
            rb.AddForce(0, 0, -Zforce * Time.deltaTime);
        }else if(X == true) {
            rb.AddForce(Xforce * Time.deltaTime, 0, 0);
        }

    }
}

This line should be if(Input.GetKey(Keycode.W)
Same for the other ‘GetKeys’.Or you could just use if(Input.GetButton("w")) but you have to register it from Project Setting > Input.

Thank you!

You definitly Helped me out, it lead me to the right path to fix it.

It turned out that everything magically fixed itself after i rewrote the entire Update function. Weird.

(Your help made the code before work too excep that it permanently Stayed at true. which actually was a Mistake i made, But after i rewrote the entire function to just assigning the Variable the function (( Example: Z = Input.GetKey(Keyode.W); Magicaclly worked after i rewrote the entire function.)

1 Like