A realy easy c# question

I have started programming c# just for a few days and i learned a bit about variables and that sort of stuff. now i have this script:
using UnityEngine;
using System.Collections;

public class AutoAttack : MonoBehaviour {

		float maxHealth = 100.0f;
	 	float curHealth = 100.0f;
		float loadingBarY = 0.9f * Screen.height;
		float loadingBarLength = 50.0f + ((Screen.width * 0.3f) * (maxHealth / curHealth));
	 	float loadingBarX = (0.5f * Screen.width) - (loadingBarLength / 2.0f);
	 	float loadingBarWidth = 50.0f;
	
	void Start () 
	{
	}
	
	// Update is called once per frame
	void Update () 
	{

	}
	
	void OnGUI()
	{
		GUI.Box(new Rect(loadingBarX,loadingBarY,loadingBarLength,loadingBarWidth), "Hello");	
	}
	
}

and i have the errors:

Assets/Scripts/AutoAttack.cs(9,76): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `AutoAttack.maxHealth’

Assets/Scripts/AutoAttack.cs(10,62): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `AutoAttack.loadingBarLength’

i’m sorry for being souch a noob, because it will probably be a simple declaration i got wrong but i can’t quite seem to find it.

Basically, you can’t define your initializers in terms of each other. Outside of any function calls, that stuff doesn’t actually execute as such- it merely defines the starting state for the rest of the script. If you want to do calculations like that on your initial values, you should do it all in the ‘Start’ method, which gets called at the very beginning of the game.

public float maxHealth = 100.0f;
float curHealth = 100.0f;
float loadingBarY = 0;
float loadingBarLength = 0;
float loadingBarX = 0;
public float loadingBarWidth = 50.0f;

void Start () 
{
    curHealth = maxHealth;
    loadingBarY = 0.9f * Screen.height;
    loadingBarLength = 50.0f + ((Screen.width * 0.3f) * (maxHealth / curHealth));
    loadingBarX = (0.5f * Screen.width) - (loadingBarLength / 2.0f);
}

Now, since ‘curHealth’ sounds like the kind of thing that would change at runtime, you should also change loadingBarLength inside of Update so that it always properly reflects how much health your character has.

void Update()
{
    loadingBarLength = 50.0f + ((Screen.width * 0.3f) * (maxHealth / curHealth));
    loadingBarX = (0.5f * Screen.width) - (loadingBarLength / 2.0f);
}

Now, a better question is-

Why is it called ‘loading bar’ when it’s obviously used for current hit points? You should make sure you give your variables accurate names, or it’ll confuse the hell out of you in pretty short order.

In C# you can’t define the initialization of variable interms of another variable.