- Home /
Public static variable not updating from void Start ()?
I have 2 scripts: Score.cs and Scoring.cs. When the public static int iScore is updated in Scoring.cs during void Start (), the variable does not change in Score.cs, although it is fine during void Update ().
Score.cs:
public class Score : MonoBehaviour
{
public Text textbox;
void Start()
{
textbox = GetComponent<Text>();
}
void Update()
{
textbox.text = "Score: " + Scoring.iScore;
Debug.Log (Scoring.iScore);
}
}
Scoring.cs:
public static int iScore;
private bool bBelow;
void Start ()
{
iScore = 0;
Debug.Log ("Start" + iScore);
bBelow = false;
Vector3 Pos = Movement2.Position;
this.transform.position = new Vector3 (Random.Range(-2, 2), this.transform.position.y);
}
void Update ()
{
float fPosition = gameObject.transform.position.y;
Vector3 Pos = Movement2.Position;
if (Pos.y < this.transform.position.y && bBelow == false)
{
iScore = iScore + 1;
bBelow = true;
}
if (fPosition >= 6)
{
//Move back to starting position
this.transform.position = new Vector3 (Random.Range(-2, 2), -6, 0);
bBelow = false;
}//end if
}
}
Hello @$$anonymous$$ ! I opened up a new project in Unity and created 2 scripts named Score.cs and Scoring.cs, assigning both of them to a Text UI element. Your code seems to be running as intended on my end; iScore is updated immediately within the Start function in Score.cs. Is there any other information you could provide to help reproduce this issue?
I'm confused, you say your Score never changes in Score.cs Start() function, but why would it? You never change the score there, you only get the reference the to text object. So what seems to be the issue here?
Answer by Huacanacha · Mar 04, 2019 at 10:57 PM
The Start method in each script will be executed in arbitrary order so it is likely WarmedxMints is correct - Scoring.Start() is running after Score.Start().
A good rule of thumb is to do internal setup in Awake (like a constructor) and anything with external interactions in Start. That way, for scripts that become active in the same frame, each scripts internal state has always been initialized.
Note: I advise against using Script Execution Order to solve sequencing issues. That creates an external dependency (script order) that is decoupled from the code itself. Static variables are also not advisable for the most part (that's a whole different discussion).
Answer by WarmedxMints · Mar 04, 2019 at 10:27 PM
This is due to script execution order. Score.cs's Start is being called before Scoring.cs's Start method. You can manually set the script execution order if it is vital the scoring is executed before score.