- Home /
Calling a variable from a different script
I've seen a few answers but no matter what I try I get no lucky
// Create an object of main menu
public MainMenu mainMenu;
public int gEnzyme;
From the MainMenu script I want to call a variable called enzyme of type int
Within the OnGUI function I assign the variable to the MainMenu variable:
gEnzyme = mainMenu.enzyme;
I've done this as I am trying to display the integer within a Box using '.ToString()'.
GUI.Box (new Rect(0, 300, 100, 50), enzyme.ToString());
I've tried all different ways of trying this even ones I feel are pointless just to see.
I've probably made a rookie error somewhere
The error I keep getting is:
NullReferenceException: Object reference not set to an instance of an object Game.OnGUI ()
Thank you in advance!
Answer by TheRaven · Nov 21, 2013 at 03:16 AM
gEnzyme.ToString() perhaps.
I assume you are calling enzyme.ToString() in a class outside of the mainmenu class.
Ignore the enzyme.ToString() forgot to repost the updated one. It does actually say gEnzyme.ToString(), but still doesn't work.
Answer by meat5000 · Nov 21, 2013 at 03:26 AM
If they are on the same object simply use GetComponent(Scriptname).variable.
If not on the same object, Find the object with GameObject.Find or FindWithTag and then use GetComponent.
Something like :
objectInstance = GameObject.Find("menuObject"); //find and store mainmenu gameobject
variableInstance = objectInstance.GetComponent(MainMenu).gEnzyme; //access variable in script on that objects's newly created instance
These are in JS, you would need the C# equivalents, which you can find in the scripting reference (or here)