- Home /
Why am I getting this error: "Keyword 'this' is not available in current context."
using UnityEngine;
using System.Collections;
public class PlayerLife : MonoBehaviour
{
public LifeState lifeState = new LifeState(this);
public class LifeState
{
private PlayerLife playerLife;
private bool currentState;
public bool alive
{
get {return currentState;}
set
{
if (value != currentState)
{
currentState = value;
if (value) playerLife.SpawnPlayer();
else playerLife.KillPlayer();
}
}
}
public LifeState(PlayerLife container)
{
playerLife = container;
currentState = false;
}
}
void SpawnPlayer() {}
void KillPlayer () {}
}
Answer by tigertrussell · Mar 12, 2015 at 02:35 PM
You need to do that in an Awake()
or Start()
method; not where you are making your properties declarations.
public class PlayerLife : MonoBehaviour
{
public LifeState lifeState;
void Awake() {
lifeState = new LifeState(this);
}
public class LifeState {...}
because the this
keyword is relative to an instance of the class, not a property of the class itself.
You're right, that worked. I guess I still don't entirely understand why, though. Aren't the initializers called when the class is instantiated? Or are only constructors called upon instantiation, and field initializers have to be statically compiled?
I found a useful page on this issue saying pretty much the same thing. Apparently it's also not allowed to initialize a variable by referencing a previously initialized field of the same class either. Didn't know that.
https://msdn.microsoft.com/en-us/library/aa645759%28v=vs.71%29.aspx
The "real" reason is that under the hood the compiler is trying to get a generic description of each class for purposes of allocating memory and understanding what to expect from other code later on down the line. When the compiler looks at your classes, the first thing it checks are the properties and the signatures of the functions to get this generic "description" of the class. At that time, you can choose to initialize a "default" value, but only if it is constant (i.e. the compiler can easily initialize it). At that point in time, things like the this
keyword are meaningless to the compiler, and there is no context under which you can refer to pre-existing code (because it hasn't compiled it yet, it's just trying to get a picture of the class).
There's some mild oversimplification and psuedoscience in that explanation, but that's the gist of it. $$anonymous$$aybe someone else in the community who knows a bit more about the lower-level stuff will chime in?
edit: oh so I guess the answer to your question is "yes" field initializers are statically compiled; constructors are called upon initialization.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
No Monobehaviour scripts in files 1 Answer
2-Dimensional Array Error [CLOSED] 1 Answer
Help I am getting an error CS0079 in my code and I don't know why. 1 Answer