Code Doubt

Hello there! I’m following up the Text101 lecture and everything is really clear.
One thing i don’t seem to get around, just to have a better understanding of code is:

Why do you have to use the declared variable like this:

text.text = “Hello World”

and not just like this:

text = “Hello World”

I don’t seem to follow why the assigned variable to type Text text has to be announced twice when writing code and deciding what to do with it.
Hope i could get this question out of my head clearly :slight_smile: and have a better understanding of the language structures.
Sincerely,
Ale

Hi Ale,

When you declare your variables you have to state the Type of that variable.

So, breaking the following down;

public Text text;

public is what is known as an access modifier, this determines the scope of access
Text in this scenario is the Type, e.g. a UI Text object
text in this scenario is the variable name

You could call the variable anything you like, best that it makes sense, but in this specific case, perhaps this would be clearer;

public Text story;

Now - the second part of your question is the .text aspect.

A UI Text object has a text field/property, e.g. the actual characters/words that will be displayed. So when you state text.text you are actually saying "the text field/property of the object referenced as text".

Again, it is easier if you rename the variable, for example;

public Text story;

and then;

void Start()
{
    story.text = "Once upon a time...";
}

Hopefully, having run through this section you will now see the importance of naming variables and methods wisely :slight_smile:

I hope this makes a little more sense now :slight_smile:


See also;

1 Like