Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Simple problem with variables

Discussion in 'Scripting' started by BobRos, Oct 3, 2015.

  1. BobRos

    BobRos

    Joined:
    Oct 1, 2015
    Posts:
    48
    I'm sure there's some extremely obvious reason for this, but I just started coding so I cant see it.
    I have to lines of code. They both are said to be correct when I build them. But then when I actually run the game...

    One works (below)

    Code (CSharp):
    1.  
    2. var instructions = GameObject.Find("GUI Text").GetComponent<Text>().text = "new text";
    3.  
    One doesn't (below)

    Code (CSharp):
    1.    
    2. var instructions = GameObject.Find("GUI Text").GetComponent<Text>().text;
    3. instructions = "new text";
    4.  

    I started coding a few days ago, so I do kind of know what variables are. And the only thing different in the second line of code is that I'm using a variable, instead of directly referring to the text. So somebody please tell me why it isn't working, it's getting extremely annoying.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    "doesn't work" as in the test component on the UI doesn't have it's value set?

    first one is the same as

    Code (csharp):
    1.  
    2. var instructions ="new text";
    3. GameObject.Find("GUI Text").GetComponent<Text>().text="new text";
    4.  
    i.e. the text attribute of the Text component is set to the new text string.

    in the second chunk you never set the Text component's text attribute is never set to anything.
     
  3. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    You want

    Code (CSharp):
    1.  
    2. var instructions = GameObject.Find("GUI Text").GetComponent<Text>();
    3. instructions.text = "new text";
    4.  
    The first way you did it just creates a local string in that method. Changing it will have no effect on the original Text object.

    The above method creates a local variable that caches the actual Text object. Then you can set the text of that object.
     
  4. BobRos

    BobRos

    Joined:
    Oct 1, 2015
    Posts:
    48
    Thanks for the help guys, I got it fixed.