Variable scope – determining where a variable can be used

Variable scope is a fancy way of saying "Where in the script a variable exists." The following screenshot explains the scope of some variables:

Variable scope – determining where a variable can be used

You might have noticed that the rectangular blocks start and end with curly braces. Just like the AddTwoNumbers() method in Chapter 2, Introducing the Building Blocks for Unity Scripts, the code between an opening curly brace and a closing curly brace is called a code block. Absolutely wherever in a code you have an opening curly brace, there will be a closing curly brace to match. All of the code between the two braces is a code block. Notice that code blocks can be nested inside other code blocks.

Note

You normally won't create bare blocks of code with curly braces like I did in the case of Code Block 3. Code blocks usually include other things, such as if statements, looping statements, and methods. This example is just to demonstrate how the scope of a variable works and where a variable exists and is usable.

The following is what you have:

Line 16: string block3 = "Block 3 text";

The preceding line declares a local string variable named block3. This variable exists in the code block that is labeled Code Block 3. If you try to use the block3 variable outside of Code Block 3, such as in Code Block 2 or Code Block 1, Unity will give you an error message saying that the block3 variable doesn't exist.

The scope of the block3 variable is the code block defined by the curly braces of lines 13 and 18:

Line 6: string block1 = "Block 1 text";

The preceding line declares a string type member variable named block1. This variable exists in the code block that is labeled Code Block 1. This code block begins on line 5 and ends on line 20. This means that the block1 variable can be used everywhere, including Code Block 2 and Code Block 3, because they are also within Code Block 1. The block1 variable is used in Code Block 2 on line 10 and in Code Block 3 on line 14.

Thus, the scope of the block1 variable is the code block defined by the curly braces between lines 5 and 20.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset