- Home /
When accessing a variable from another script it is always equal to 0.
Hi everyone, I am having trouble accessing a variable from another script, I know the problem is that my variable is public and set in the inspector and so it is 0. But how can I access this variable without getting 0 ? Here is the code for the "thePos" variable that I want to access: // Start is called before the first frame update
private Vector3 thePosition;
public Vector3 thePos;
void Start()
{
//Debug.Log(thePos);
}
// Update is called once per frame
void Update()
{
//Debug.Log(thePos);
thePosition = transform.position;
thePos = transform.TransformDirection(new Vector3(thePosition.x,thePosition.y,0));
}
You said "I know the problem is that my variable is public and set in the inspector and so it is 0", but that is not how it works. The fact that the variable is public and appears on the inspector won't make it 0. $$anonymous$$y guess is that your transform is at the position (0,0,0)? try changing the position of the object this script is attached to. If you do that, "thePos" value should change, and it will be different than zero in the inspector too.
Answer by sacredgeometry · Dec 22, 2020 at 03:24 AM
Private fields are not accessible from outside of your script at all.
Public serialisable fields are initially set to their default or initialised values but then all subsequent values are taken from the inspector.
If you want to reference a value from the inspector you need to get a reference to the specific object and its instance of that component and then grab the values from it.
Your answer
