- Home /
ERROR: A field initializer cannot reference the nonstatic field, method, or property `CameraPosition.runner'?
Hello, I am new to scripting and I am trying to create a C# script for the Main Camera so that it will follow a Runner game object by it's X axis position. The Runner has it's own scripts that controls it's movement, while at the same time I do not want the Main Camera to be a child object of Runner so as to prevent it getting disabled from a script. However, when I tried to press play, I get a compiler error that read: "A field initializer cannot reference the nonstatic field, method, or property `CameraPosition.runner'". What does this error mean and what do I need to do? Thank you.
My script:
using UnityEngine;
public class CameraPosition : MonoBehaviour {
private GameObject runner = GameObject.Find("Runner");
Vector3 runnerPosition = runner.transform.position;
void Update () {
transform.localPosition.x = runnerPosition.x;
}
}
Answer by robertbu · Jul 28, 2013 at 03:29 AM
You need to move your initialization inside Start() or Awake():
using UnityEngine;
public class CameraPosition : MonoBehaviour {
private GameObject runner;
Vector3 runnerPosition;
void Start() {
runner = GameObject.Find("Runner");
runnerPosition = runner.transform.position;
}
void Update () {
transform.localPosition.x = runnerPosition.x;
}
}
Because field initializers are executed before the actual constructor of a class is called. Therefore the object isn't even created / initialized yet. Apart from that the actual construction of the classes is done in Unity's loading thread. That's why you generally shouldn't use code that isn't thread safe in a field initializer or constructor of a class.
Your answer
Follow this Question
Related Questions
2D Game Checkpoint & Respawning 2 Answers
Varying behaviour of transform.position.localPosition.x in StateMachineBehaviour OnStateUpdate 1 Answer
Animate from instantiated GameObject 0 Answers
Does it help performance to first check if some transform attribute has changed before setting it? 1 Answer
transform.position not setting position OR animation setting position even though it shouldn't 0 Answers