I am running multiple OnGUI()s in different scripts and trying to control them with a static var that I have declared only once, in the first script.
If I change this var in a second script, and directly call the var on the first script using:
myScreen.GetComponent(“Welcome_script”).displayFlag1 = 1;
it works fine.
However, just changing the variable in the second script is not enough to be recognised in the other script, even thought the first script is continually being called.
Am I misunderstanding the global nature of static var?
To clarify, I suppose I am asking about the scope of a static variable.
Since OnGUI is called every frame, why can’t a static variable declared as part of this script, but altered in another script, be automatically be “seen” by the first script?
(I understand directly referencing as in
if (SomeScript.someVariable == 1) {print (“It’s one!”);} but I don’t want to manually reference every script that will be dependent on the static variable.)
Is there a better Global variable that is visible to any script?
Static variables can be accessed anywhere, you just need to prefix the variable name with its containing class.
To create the static variable (lets say I want to make my members ID available to any class/script):
public class myGlobalScript : MonoBehaviour
{
//Static variables used across the application
public static string MemberLoginID;
}
Then, when I want to access the MemberLoginID variable, I call it (from any class/script) using the following:
//Set the static varible
myGlobalScript.MemberLoginID = "Spongebob";
//Check the static variable
if(myGlobalScript.MemberLoginID =="Spongebob") DoSomeFunction();
EDIT: Loran, you can also setup static references to GameObjects that you use frequently. Something like:
public class myGlobalScript : MonoBehaviour
{
//Static references to guiObjects
public GameObject m_GenericMessageBox;//We can change this in the inspector
public static GameObject GenericMessageBox;//We reference this at runtime
void Awake()
{
GenericMessageBox = m_GenericMessageBox;//Assign what was in the inspector to the static GameObject
}
You can drop the GameObject.Find() and just use “myGlobalScript.GenericMessageBx” Note that the example is C#. So if you want to access the GO’s script, the method is somewhat different between JS and C#.
There aren’t really any performance differences between C# and JS, they are both compiled to MSIL anyway. For Unity, JS is probably the easier language to learn, since all the documentation examples use it and from what I remember, accessing a GameObjects script is slightly simpler.