- Home /
Public Variable not updating
Recently I've hit a roadblock with my current project, where, in essence, I need a float to be accessible from other objects, while still being able to be updated in script, that way when another object calls upon it through Get Component, it gives the updated variable.
//The Object Script that holds the variable
public float distanceToPlayer
public void calculateDistanceFromPlayer(){
GameObject player = GameObject.FindGameObjectWithTag("Player");
Vector2 playerPosition = new Vector2 (player.transform.position.x, player.transform.position.y);
Vector2 tilePosition = new Vector2 (transform.position.x, transform.position.y);
float distanceToPlayer = Mathf.Floor(Vector2.Distance (playerPosition, tilePosition));
}
And the code that is accessing the above code
// Closest possible to player
float cptp = 0;
public List <TileScript> selectableTiles = new List <TileScript> ();
public List <TileScript> cptpList = new List <TileScript> ();
foreach (TileScript TS in selectableTiles) {
if (TS != null) {
if (TS.distanceToPlayer < cptp) {
Debug.Log ("Test One");
cptpList.Clear ();
cptpList.Add (TS);
cptp = TS.distanceToPlayer;
} else if (TS.distanceToPlayer == cptp) {
Debug.Log ("Test Two");
cptpList.Add (TS);
}
}
}
I've been trying to look at different errors, and from what I've gathered, distanceToPlayer is not updating. The code for it works, but it doesn't update the objects code (I've used Debug.Log, and each tile has said how far away it is from the player, but when I call it from outside of calculateDistanceFromPlayer(), it states 0) It seems that I need it to be both a public, and not public variable at once, is their any way to force it to update from within the code? I appreciate any help on the mater, thank you in advance. -Sincerely, Eve
Answer by Cornelis-de-Jager · Jan 18, 2019 at 05:54 AM
You are creating a new Local variable with the same name as your public variable. So When you update it you only update the local variable - not the global one.
public float distanceToPlayer; // <- this is the one being accessed
public void calculateDistanceFromPlayer(){
...
float distanceToPlayer = Mathf....; // This is a new local variable
}
Solution:
// Solution : Remove the float
/* float */ distanceToPlayer = Mathf.Floor(Vector2.Distance (playerPosition, tilePosition));
Extended Solution
public void calculateDistanceFromPlayer(){
GameObject player = GameObject.FindGameObjectWithTag("Player");
Vector2 playerPosition = new Vector2 (player.transform.position.x, player.transform.position.y);
Vector2 tilePosition = new Vector2 (transform.position.x, transform.position.y);
distanceToPlayer = Mathf.Floor(Vector2.Distance (playerPosition, tilePosition));
}
Thank you for the help! I was without Internet, so I found another solution (I deleted the public variable, and told it to return the variable specifically), this helps explain why I didn't come across the problem again later when I thought I did the same thing as before.