Click here to Skip to main content
15,888,006 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
My code is:
C#
public class PublicPrivate : MonoBehaviour {

	public float level = 10f;      
	float health = level * 10f;  

	void Update () {
		if (health <= 0) {
			Debug.Log ("You have died.");
		}
	}

However, when I debug, it tells me:
C#
    public float level = 10f; 
	float health = level * 10f;
A field initialiser cannot reference the non-static field, method, or property 'PublicPrivate.level' 

I understand why, but I can't figure out what I should change my 'health' variable to since a float or int won't work. Any ideas? Currently learning C# so please forgive me if this question has an obvious answer.

What I have tried:

I've tried changing it to an int and a double, neither worked. Not too sure what else to try.
Posted
Updated 14-Nov-16 10:55am

The other two Solutions are correct, you cannot use one field to initialize another. For this case, however, there is very a simple solution, define a constant for the default level value and initialize both based on that:
C#
public class PublicPrivate : MonoBehaviour {
  const float defaultLevel = 10f;
  public float level = defaultLevel;
  float health = defaultLevel * 10f;

You could even do better, by getting rid of as many in-line constants as possible in favor of a clearly named constant, and have:
C#
public class PublicPrivate : MonoBehaviour {
  const float defaultLevel = 10f;
  public float level = defaultLevel;
  const float levelToHealthFactor = 10f;
  float health = defaultLevel * levelToHealthFactor;  
 
Share this answer
 
The problem is not the type of variable. You cannot have a field variable in a class being initialised by another field variable. It means that you are not allowed to use level for the initialisation of health.
 
Share this answer
 
v2
This is because :

You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException.


You can read more details about it at this link

one of the solution is to move the second variable initialization in the constructor, or both variables initialization like:

C#
public class PublicPrivate : MonoBehaviour {
 
	public float level;      
	float health;

        public PublicPrivate()
        {
           level = 10f;
           health = level * 10f;
        }  
 
	void Update () {
		if (health <= 0) {
			Debug.Log ("You have died.");
		}
	}


you can also refer to this question
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900