Can you make a global reference to a rigid body?
I want to make a reference for the rigid body that I can manipulate in multiple functions. Right now I get this error
Assets/Scripts/CubeMovement.cs(11,32): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.GetComponent()'
Here is my file
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CubeMovement : MonoBehaviour {
public GameObject Cube; //The Cube
public float speed;
public float forwardSpeed;
public float jumpSpeed;
static Rigidbody rb = GetComponent<Rigidbody>();
// Update is called once per frame
void Update ()
{
//Cube.transform.position += new Vector3 (0f, 0f, .5f);
//if you want to make it so it is whatever the script is attatched to, instead of "Cube.transform.position"; Do gameObject.transform.position
//Also instead of 1f, 0f, 0f
//You can customize it to whatever you want (x,y,z)
//If you do decimals do "f" don't just do "5.4" do "5.4f"
//This is in the update function, it will happen per frame. Feel free to have it in any other function :)
}
void FixedUpdate ()
{
//Rigidbody rb = GetComponent<Rigidbody>();
if (Input.GetKey("a"))
{
rb.AddForce (-Vector3.right * speed * Time.deltaTime);
}
if (Input.GetKey("d"))
{
rb.AddForce (Vector3.right * speed * Time.deltaTime);
}
rb.AddForce( new Vector3(0,0,forwardSpeed*Time.deltaTime));
}
//function that will make the cube jump
void Jump()
{
rb.AddForce(Vector3.up * jumpSpeed);
}
/*
void LateUpdate() {
Cube.transform.position += new Vector3 (0f, 0f, .5f);
}*/
}
Comment
private Rigidbody rb ;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}