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