Variables are a means of storing data for later use. They are one of the core pillars of programming. It may help you to think of a variable as a box.
It has a name used to access the value, and the value that is stored. Variables come in different types, today we'll be handling 3 families of variables. Words, Numbers, and True/False (in programming called a Boolean). With the exception of Booleans, these are not typically grouped like this, and are only being done so now as a teaching tool. For Words your primary type of variable is a string. A string holds whatever characters you want it to, and is enclosed in ""s. An addition type is char, which is a single character. char's are enclosed in ''s.
If we go back to the program we made last week, we now know some of what we need to make a change.
Change
Code: Select all
void Start () {
Debug.Log("Hello world!");
}
To
Code: Select all
void Start () {
string message = "Hello world!";
Debug.Log(message);
}
And run the program again. You should see the same message as last time.
As I said previously "Hello world!" is a string value. We know this because it's enclosed in ""s. What's new here is
This has several parts which I will now break down.
'string': This is the type of the variable we wish to declare.
'message': This is the name of the variable we wish to declare, we can then use it in the future to represent the stored value.
'=': This is the assignment operator. This may be confusing for people with a math background. Thinking of it as a traditional equals sign can get you in trouble. It means set the value of what's on it's left side to the value of what is on it's right side.
'"Hello world!"': This is the value we assign to message using '=' the assignment operator.
At this point I encourage you to play around a bit, entering your own string values.
Above we declared and assigned the variable in the same line. This is common, but not the only way to do things. You may not know the value a variable will have at the time it's being declared. In such cases you can break it up
Code: Select all
string message;
message = "Hello world!";
Note that string is not repeated at the beginning of future references to message, only when it's first declared, and that you need to end each line with ";" the line terminator. If you are observant you'll notice that this isn't true of all code by looking at other parts in this file, but for now, everything you do inside of 'Start' will require it.
Try one final example to help understand variable assignment
Code: Select all
void Start () {
string message;
message = "Hello world!";
Debug.Log(message);
message = "Hello world Again!";
Debug.Log(message);
}
At this point if you feel you don't understand variable assignment, please ask one of the teachers in discord.
That will cover strings for now, but as I said above, we are also covering Numbers, and booleans.