Search Unity

How to call global variables?

Discussion in 'Scripting' started by W4RH4WK117, Apr 7, 2012.

  1. W4RH4WK117

    W4RH4WK117

    Joined:
    Feb 6, 2011
    Posts:
    129
    Hey,

    I was reading over how to set up global variable in Javascript on the API, although it's told me how to create a global variable it hasn't told me how I can call that variable in another script. So as an example let's say I have script 1 that holds currency for money which I have set as a global variable. I make a script two which makes it so I can Instantiate a house but only if I have the correct amount of money, how can I call global variable to check for the money?

    Hope this makes sense.
    Thanks.
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
  3. W4RH4WK117

    W4RH4WK117

    Joined:
    Feb 6, 2011
    Posts:
    129
    That sort of helps but doesn't explain how to do it very well.
     
  4. joaonaveia

    joaonaveia

    Joined:
    Apr 3, 2012
    Posts:
    5
    Try That:
    Code (csharp):
    1.  
    2. //This is the Global Variable
    3. var vari = "I'm a Global Variable";
    4. //call the function for when the scene starts.
    5. function Start(){
    6. //This is a local variable
    7. var localvar = "Local variable";
    8. //print the global variable
    9. Debug.Log(vari);
    10. //But Don't print the local variable
    11. }
    12.  
     
    Last edited: Apr 7, 2012
  5. Amon

    Amon

    Joined:
    Oct 18, 2009
    Posts:
    1,384
    Ok! This is what you need to do. Hopefully after reading this you'll understand how to grab other scripts from other scripts and modify their stored data.

    Step 1: Open the Unity Editor >> Very important this one. :)

    Step 2: Using the Top Menus, Select "GameObject" Then "CreateOther" and select Cube. Do it again and select Sphere. Place them apart in the editor opposit eachother.

    Step3: Create 2 JScripts and name one "ScriptWithGlobal" and the other "ScriptToAccessGlobal". Sorry for the names but it's just to super simplify things.

    Step 4: Drag the "ScriptWithGlobal" script on to the sphere object and the "ScriptToAccessGlobal" on the cube object.

    Step 5: Below is the Code you put in the "ScriptWithGlobal" script. Basically it has a normal var that is called TheGlobal. This is the global we are going to access from the other script and change its value. The next bit in the script is just a simple transform on the x axis moving the sphere. We are going to access the value of "TheGlobal" variable from the other script and make the sphere switch direction and go the other way. :)

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var TheGlobal:float;
    5.  
    6. function Start () {
    7.     TheGlobal = 1.5;
    8. }
    9.  
    10. function Update () {
    11.     transform.position.x += TheGlobal * Time.deltaTime;
    12. }
    13.  
    Step 6: The code below goes in to the "ScriptToAccessGlobal" script. What's going on in this one then, you may say! We set up another variable called, I've named it something silly but it's again only to super simplify things, "GrabThatBlettyGlobal". "Bletty" is a nicer way to say "Bloody". :) Now this var has to be of type "GameObject" because what we are grabbing with it is the Sphere GameObject we created in Step 2. Next you'll see how we grab the Sphere GameObject. It's as simple as "GrabThatBlettyGlobal = GameObject.Find("Sphere");" GameObject.Find("Sphere") will look for a GameObject called Sphere. We have one called Sphere because we created it via the menu in Step 2 and left the default name for it.

    Once it finds the Sphere GameObject we can then begin to access the script "ScriptWithGlobal which is a "component" of the Sphere GameObject. It is the script we attached to the sphere. So once we grab the GameObject we can then use the "GetComponent" part of it all to grab the script and have access to all its values from within this script. :)

    It's a simple as "GrabThatBlettyGlobal.GetComponent(ScriptWithGlobal).TheGlobal = -1.2;"

    In the line above we start with our "GrabThatBlettyGlobal" followed by a "." . It's just like doing transform.position! We are using the "." to access the GameObject Components stored in "GetThatBlettyGlobal" that we grabbed with "GameObject.Find.

    After the dot we use "GetComponent" to access a specific component of the Sphere GameObject. And what we want is the script attached to the Sphere GameObject which is called "ScriptWithGlobal". :) after that another dot lets us access what we want and that is the Global var in the script "ScriptWithGlobal" which is funnily enough called "TheGlobal. From there we change the value by adding the minus sign before the value thus changing it. :)

    Oh! nearly forgot. I set it up so that the sphere will walk away from the cube until you press the G button on your keyboard. I picked the G key because it's not nice that rude Mr Sphere walk away from Mr Cube when its talking to it so the G key means "GetbackHere!" Anyway enough of the stupid little story as I'm not funny at all, but upon running this in Unity the sphere will move away from the cube until you press G then the sphere will switch direction and start going toward the cube.

    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var GrabThatBlettyGlobal:GameObject;
    5.  
    6. function Start () {
    7.     GrabThatBlettyGlobal = GameObject.Find("Sphere");
    8. }
    9.  
    10. function Update () {
    11.     if ( Input.GetKeyDown(KeyCode.G) ) {
    12.         GrabThatBlettyGlobal.GetComponent(ScriptWithGlobal).TheGlobal = -1.2;    
    13.     }
    14. }
    15.  
    Have fun and if there is anything else that needs further clarification please jsut post and ask. Also i wrote it like this not for the capable already, but for the soon to be capable with GameObjects and accessing script and values from other scripts. :)

    Ta!
     
    Last edited: Apr 7, 2012
  6. W4RH4WK117

    W4RH4WK117

    Joined:
    Feb 6, 2011
    Posts:
    129
    Cheers, for that. Helped me big time.

    Just also wondering how can I call more than variable at the same time? would it be like

    Code (csharp):
    1.  
    2. GrabThatBlettyGlobal.GetComponent(ScriptWithGlobal).TheGlobal  TheGlobal2  TheGlobal3 = -1.2;
    3.  
     
    Last edited: Apr 7, 2012
  7. Amon

    Amon

    Joined:
    Oct 18, 2009
    Posts:
    1,384
    Hey, Sorry for the late reply. yes it would be like that but not exactly like that. Your guess is correct to 99%. :)

    You need to do the same for TheGlobal2 and TheGlobal3 as you did for TheGlobal otherwise the compiler will not know where TheGlobal2 or TheGlobal3 is. I don't mean regetting gameobjects getcomponents just access the second and third globals the same way you accesed the first, so, your above code should be like this:


    GrabThatBlettyGlobal.GetComponent(ScriptWithGlobal).TheGlobal = -1.2;
    GrabThatBlettyGlobal.GetComponent(ScriptWithGlobal).TheGlobal2 = -1.2;
    GrabThatBlettyGlobal.GetComponent(ScriptWithGlobal).TheGlobal3 = -1.2;
     
    Last edited: Apr 7, 2012
  8. Tseng

    Tseng

    Joined:
    Nov 29, 2010
    Posts:
    1,217
    Please, do not spread false knowledge around and confuse beginners even more. Your "vari" variable, is not a global variable, it's a member variable.

    It's only valid for a certain instance. The global variable (which is a misleading term, as it's not used anymore since the times of C++) is actually a static variable which is not tied to an object instance.
    It would be good if people would stop referring to them as "global variables" because that's wrong, global variables do not exist in full OOP langauges like C# and Java, because it's impossible to declare a variable outside of a class body.

    To access public member variables you need to obtain a specific instance of that specific object (usually by GetComponent in Unity or getting a reference).

    A local variable is only valid inside the { }-block it was defined.

    Unity(Script) "Member vs Global Variables"
     
  9. Hakimo

    Hakimo

    Joined:
    Apr 29, 2010
    Posts:
    316
    Hi Tseng,

    I've always thought when someone says "global variable", it means it's just global to that scope of that script itself and that it only applies to the object you attach it to. Whenever someone mentions static variable, it basically means sharing that variable information with other objects. That's what I thought that is.

    Thanks for explaining it clearly though about the differences. I've read about discussions using global variable in OOP and it almost seems like a taboo thing. Is it really impossible to declare a variable outside a class? In terms of coding for games, what's a good way to do this? Would you make a class where all the main variables of a game are listed then access it using components?

    Hope you don't mind me asking :)
     
  10. MADmarine

    MADmarine

    Joined:
    Aug 31, 2010
    Posts:
    627
    If you really want to imitate global variables, you can create a class (let's call it Globals), and just create static variables inside it, e.g. static int staticVar.

    You'd then be able to access those variables anywhere in the program using something like Globals.staticVar.

    Although this obviously still comes with all the classic pitfalls of global variables in C++.
     
  11. Tseng

    Tseng

    Joined:
    Nov 29, 2010
    Posts:
    1,217
    There are basically 4 variable scopes

    Local Variable: They are only valid within the { } block
    Member Variable: valid for the whole class (can be access via this.myVarName or just myVarName if no localvariable of same name exists)
    Static Variable: bound to a class/type (can be access by ClassName.myStaticVariable)

    Global Variable: Exist everywhere. Do not exist in pure OOP languages, because everything must be organized Types (classes, structs, etc.) and namespaces. Global variables had issues with naming conflicts. One of the reasons why it do not appear in pure OOP languages


    Code (csharp):
    1.  
    2. public class Test : MonoBehaviour {
    3.     private static string staticVar = "I am a static variable";
    4.     private string testVar = "I am a member variable",
    5.  
    6.     private void Start() {
    7.         if(true) {
    8.             string testVar = "I am a local variable";   // only valid within the if-code block!
    9.             Debug.Log(testVar); // Prints: I am a local variable
    10.             Debug.Log(this.testVar); // prints: I am a member Variable;
    11.         }
    12.  
    13.         Debug.Log(testVar); // prints: I am a member variable
    14.         Debug.Log(Test.staticVar); // prints: I am a static variable
    15.     }
    16. }
    17.  
    Notice that "Debug.Log(testVar);" prints two different lines, depending whether it's inside a block which has a local variable (inside the if - then it uses the local variable) or if it's outside of a block which contains a local variable with the same name (then it uses the member variable). If you want to specifically access a member variable, when there is a local variable with the same name, you put "this." in front of it.