Hi,
I just wanted to know how to set a variable accessible from all the scripts
When I create a script with a variable, I can’t access to it’s informations or modify it through other scripts…
How can I deal with it ?
Thanks
Hi,
I just wanted to know how to set a variable accessible from all the scripts
When I create a script with a variable, I can’t access to it’s informations or modify it through other scripts…
How can I deal with it ?
Thanks
Hi @Rtbots ,
There are a few ways you can do it, I’ll first list a few options, details a bit later:
A public field:
public int w;
Properties (get/set):
private int _y;
public int y
{
get { return _y; }
set { _y = value; }
}
Properties (get/set, lambda style. Same as above, just a bit different syntax):
private int _x;
public int x
{
get => _x;
set => _x = value;
}
Static field:
public static int z;
Now, to access these from another script, you could do it like this:
public class OtherScript : MonoBehaviour
{
// The C# class we want to access
// i.e. your script:
public Script script;
}
Just drag the other object with the desired script (in this case “Script” type) to the slot in Inspector.

Now you can access the script object. You do it like this:
// Use it when it's been assigned to a public field:
Debug.Log("x in script: " + script.x);
If you want to get a component, so that you don’t assign them in Inspector, you could:
// Get a component of type Script in an object called "Object":
Script s = GameObject.Find("Object").GetComponent<Script>();
To use those properties (get/set):
// Access a script property (get/set):
Debug.Log("y in script: " + s.y);
To access that public field I listed first:
// Access a public field:
Debug.Log("w in script: " + s.w);
And to access a static field, you can use:
// Access a static field:
Debug.Log("static z in Script: " + Script.z);
Thank you so much !!!
Refresh page if I fix some details ![]()
But I think this will get you a few options to get things rolling.