Reputation: 45
As you can see I am trying to create a vector3 variable that stores the position of the gameobject and I'm getting the following error:
A field initializer cannot reference the non-static field, method, or property
I have tried turning the gameobject into static variable but then I get another error inside Unity:
NullReferenceException: Object reference not set to an instance of an object
How can I fix this?
public GameObject playerobject;
private Vector3 playerposition = playerobject.transform.position;
Upvotes: 2
Views: 1396
Reputation: 125375
You have to initialize the playerposition
in a function instead of where it is declared. The Start
or Awake
function is fine for this. If you need to update the playerposition
variable every frame then do it in the Update
function. The reason for this is that the variable you use to initialize another variable outside a function must be a static
or const
variable.
I am sure you don't want the playerobject
to be static
or const
because you want to assign it in the Editor so doing it in a function is the correct way to do this.
public GameObject playerobject;
private Vector3 playerposition;
void Awake()
{
playerposition = playerobject.transform.position;
}
After that, make sure to apply an Object to thethe playerobject
slot in the Editor.
Upvotes: 2