- Home /
Static variable work in one script but not in the other
So I have this static variable
public class GenerateCupScript : MonoBehaviour {
public static string objectName;
public void Start () {
objectName = "Test";
}
}
A script calling the variable
public class WaterTapScript : MonoBehaviour{
public string objectName;
void Start() {
objectName = GenerateCupScript.objectName;
}
}
And another script calling the same variable
public class BarForCup: MonoBehaviour{
public string objectName;
void Start() {
objectName = GenerateCupScript.objectName;
}
}
The problem is the WaterTapScript can call the value from the GenerateCup but the BarForCup can't do that. If the BarForCup call GenerateCupScript.objectName it will return null, but the WaterTapScript will return "Test". And this is how I tried to fix the problem but none work
1
attaching BarForCup script to the same object the GenerateCupScript is attached
2
attaching BarForCup script to the same object the WaterTapScript is attached3
use Awake
4
public string objectName = GenerateCupScript.objectName;
5
call it at the same time in Awake, Start and using 4
Answer by LeonardNS · Oct 07, 2018 at 11:16 PM
Unless otherwise is instructed, the running order on scripts is quite random. What I think has happened is that one of the scripts trying to access the variable ran first, then the script with the variable, and at last, the script that actually works. In Edit > Project Settings > Script Execution Order you can change the order of which script are executed. All of your referencing happens in Start, or about the same time. Moving the GenerateCupScript to run before the rest might solve your problem.
@LeonardNS is right. Although, I would suggest not to mess with Execution Order unless you really have to. You could rather initialise your static variable : 1. with a default value. 2. on Awake ()
public static string objectName = "test"; // default value
void Awake ()
{
objectName = "Test";
}
Thank you very much, I'm new to Unity so this is the first time I heard about the Script Execution Order.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Help me finish my room generator 0 Answers
How to shorten multiple if statements ? 2 Answers
How do I reference a class to pass on variables in that class? 0 Answers
Distribute terrain in zones 3 Answers