Getting error when initializing Rigidbody, A field initializer cannot reference the nonstatic field, method or property.

I created a simple script for a ball. The principle is, when I press space, it activates gravity and it falls, then respawns to another position, with gravity turned off, waiting to press Space to fall again. I followed the code on the scripting API page for Rigidbody, but I still get this error:

" Assets/Custom/sphereBehaviour.cs(7,31): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `sphereBehaviour.ball’ "

Here’s the code:

public class sphereBehaviour : MonoBehaviour {

	public GameObject ball;
	public Rigidbody rb = ball.GetComponent<Rigidbody>();

	// Use this for initialization
	void Start () {
		ball = GameObject.Find ("Sphere");
	// Update is called once per frame
	void Update () {

		rb.useGravity = false;

		if (Input.GetKeyDown (KeyCode.Space))
			rb.useGravity = true;

		if(ball.transform.position.y < 1f)
			ball.transform.position = new Vector3 (0, setRndHeight (), 0);

	float setRndHeight() {

		float rndHeight = Random.Range (3f, 11f);

		print ("Ball height is " + rndHeight);

		return rndHeight;


you can’t do this:

public Rigidbody rb = ball.GetComponent<Rigidbody>();

outside of a function. change it to:

public Rigidbody rb;

then add the following into Start()

rb = ball.GetComponent<Rigidbody>();