Search Unity

Change variable in other script

Discussion in 'Scripting' started by herbie, Aug 10, 2015.

  1. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    I have two scripts:

    script1:
    Code (JavaScript):
    1. public var Variable1;
    2. public var Variable2;
    3. public var Variable3;
    4. //etc.
    5.  
    6. function Update()
    7. {
    8.     if (Variable1 == true)
    9.     {
    10.         //blabla
    11.     }
    12.     if (Variable2 == true)
    13.     {
    14.         //blabla
    15.     }
    16.     if (Variable3 == true)
    17.     {
    18.         //blabla
    19.     }
    20.    
    21.     //etc.
    22. }
    23.  
    24.  
    script2:
    Code (JavaScript):
    1. public var otherScript: script1;
    2. private var X: int;
    3.  
    4. function Start ()
    5. {
    6.     X = Random.Range(1,4)
    7.     otherScript.Variable'X' = true;
    8. }
    Of course this is not working because "Variable" is not part of script1.
    But how can I do this? I know this must be possible. Something like converting int to string?
     
  2. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    in second script:
    Code (CSharp):
    1. Script1 script1; //first part is name of script1 and second can be anything as it sets variable name so you can use later
    2.  
    3. script1 = gameObject.GetComponent<Script1>(); //this goes in start function and stores reference to script1 from gameobject (in this example it assumes script1 is in same gameobject)
    4.  
    5. script1.variable1 = 1; //sets variable 1 of script1 to 1
    this is for c# and is one example to refference scripts
     
  3. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    Thanks for reply.

    I'm not quite familiar with c# but what I mean is that in script2 the variable X is different everytime you start the script (it's 1, 2 or 3).
    When X = 1 in script2, then "Variable1" in script1 must be true.
    When X = 2 in script2, then "Variable2" in script1 must be true.
    etc.
    So in script2 you actually need the code:
    Code (JavaScript):
    1. otherScript.Variable1 = true;
    or
    Code (JavaScript):
    1. otherScript.Variable2 = true;
    How can I put otherScript.Variable and X together?
    otherScript.Variable+X or
    otherScript."Variable"+X or
    otherScript.Variable+"X" or ...

    I know there must be a way.
     
  4. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    oh
    Code (CSharp):
    1. if(x == 1)
    2.    script1.variable1 = true;
    3. else if (x == 2)
    4.    script1.variable2 = true;
    5. else
    6.    script1.variable3 = true;