In this Unity Tutorial we will talk about "Access Modifiers", how to implement them, and we will learn how to perform simple mathematical operations using "Variables" and "Constants".
Unity Tutorial Level: Beginner.
5.1 Access Modifiers.
These "Modifiers" help us to define the accessibility that the Members of a Class will have (in other words, let us know who can see the Variables that we have created, or Methods, and so on).
At this point, we will see the Access Modifiers "Public" and "Private" (there are others, but for this tutorial series these two will be the ones that we will use the most).
"Public" Modifier.
By assigning it to a Class Member (for example, to a Method), it allows access to it from another Script (or from another Class). This can only be achieved if there is an Instance of the first Class running at the time of requesting access (in next tutorials, we will see how to carry it out).
Example: In a Script, create a Variable that contains the "X" axis position of our character, this position is needed to be read by other codes (for example, the Script of an enemy character).
public float characterPositionX;
Note: When the "Public" Access Modifier is assigned to a Variable, and this is within a Class belonging to "MonoBehaviour", the "Value" of that Variable can be modified from the Unity Editor Interface (from the "Inspector" window).
"Private" Modifier .
By assigning it to a Member of a Class, it allows access to it only from within the same class.
Example: Create a Constant that contains our character jump force, this constant can only be used within our Class (it can not be read by others).
private const int characterJumpForce = 15;
Note: When we create a Class Member and "do not specify" an Access Modifier, this Member will behave as if it had a "Private" Modifier; from the previous example, we would have the same behavior if we had created the Constant in the following way:
const int characterJumpForce = 15;
Another aspect to take into account when we declare Variables and Constants with "Public" or "Private" Modifier type is, to do it within the body of our Class, but not within a Method (since the variables declared within a Method can not be used in other parts of the Class, only within the same Method).
If you want to know more about the Access Modifiers you can visit https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers .
5.2 Creating a new Script.
Create a new Script named “BasicOperations”, then add it as a “Component” of our “GameObject”, finally, remove any other component that is an instance of a different Script.
Now, open our Script "BasicOperations" in the Code Editor; another way to open the code files is to do it from the "Inspector" window (when there is an instance of our Script added as a component), just click on the small gear that is in the upper right corner of the component and choose "Edit Script".
5.3 Additions and Subtractions.
Next, we will begin to perform simple mathematical operations using Variables and Constants. The first step is to have our "BasicOperations" script open in the code editor
To perform the "Addition" and "Subtraction" Operations, is necessary to use the Arithmetic "Operators" (the symbols that define the action to be carried out):
-
Addition: "+" ("add" or "positive" symbol).
-
Subtraction: "-" ("less" or "negative" symbol ).
"Addition" Operation.
First, create the following Class Members (Variables and Constants):
public int firstValue; public const int secondValue = 10; int operationResult;
Note: When creating a Variable, is possible to assign it a value or not (in this case, firstValue and operationResult were created without a specific value, when executing the code, these variables will start with the value of "zero" , and the values will be maintained until some line of code appears to modify them). Constants, they must always be created with an assigned value, otherwise an error will be generated (see the following example, where the Constant "secondValue" is registered without assigning a value).
Now, let's write the following inside the “Start” Method:
void Start () { operationResult = firstValue + secondValue; Debug.Log("Addition Operation Result = " + operationResult); }
Save the code file and switch to the Unity Editor Interface.
In Unity, if you click over “GameObject” (inside the “Hierarchy” window) and then see its Components (inside the “Inspector” window), you will see the next:
You can see that inside the "Basic Operations" component (which is the Instance of the "BasicOperations" Class) it shows a field called "First Value". This field is the Variable "firstValue" that you created in your Script; and it becomes visible within the Unity Editor Interface for three reasons (which all must always be fulfilled): to be a Variable, to be created with the "Public" Access Modifier and the Class that contains this variable has to belong to "MonoBehaviour".
Note: The Constant "secondValue" although it was also created with the "Public" Access Modifier, is not shown in the Unity Edition Interface because it is a Constant (and not a Variable).
The fact that we can see our Variable in the Unity Editor Interface is very useful for us; since this means that we can modify its value from this environment without having to open the code editor.
Before making any changes, let's execute the scene. The Unity's Console will show the following:
A result equal to "ten" is indicated (which is the value of our Constant "secondValue") because our Variable "firstValue" has a value of "zero".
Stop the scene's execution.
Now, from the Unity Editor Interface let's change the Variable “firstValue” value (from “0” to “40”):
Re-run the scene, you can see that the Console shows:
The "Addition" Operation was carried out correctly (40 + 10 = 50).
"Subtraction" Operation.
After stopping the scene, open the code editor and make a modification so that a "Subtraction" is now carried out (firstValue - secondValue):
void Start () { operationResult = firstValue - secondValue; Debug.Log("Subtraction Operation Result = " + operationResult); }
Save the code file and switch to the Unity Editor Interface.
In Unity, run the scene (without making changes). The Unity's Console will show:
We can see the "Subtraction" operation was carried out correctly (40 - 10 = 30).
Note: The values assigned to "Public" type Variables within the Unity Editor Interface, will overwrite those that are inside the code editor (even if the Variable is created with a specific value within the code editor, if we change this value in the Unity Editor Interface, this new value will be used when executing the code).
Operations with "String" Data Types.
Is time to modify the Class Members:
public string firstValue; public string secondValue; string operationResult;
Inside the “Start” Method:
void Start () { operationResult = firstValue + secondValue; Debug.Log("Addition Result = " + operationResult); }
Save the code file and switch to the Unity Editor Interface.
Now, the “GameObject” Component will look like this:
In the “First Value” field, let's type “This is a“.
In the “Second Value” field, let's type “ Group of Words“ (add a "space" at the beginning).
Run the scene, the Unity's Console will show:
We can see the "Addition" of "String" type Variables was carried out successfully.
Nota: En el caso de la “Sustracción”, no se puede realizar con Variables tipo “String” (no como lo hicimos con la “Adición”).
Note: For "Subtraction" operation, it can not be done with "String" type Variables (not as we did with the "Addition").
5.4 Multiplications and Divisions.
To perform the "Multiplication" and "Division" Operations, in addition to the Variables, is necessary to use the following Arithmetic Operators (the symbols that define the action to be carried out):
-
Multiplication: " * " ("asterisk" symbol).
-
Division: " / " ("slash" symbol).
"Multiplication" Operation.
Let's modify again the Class Members:
public float firstValue; public int secondValue; int operationResult;
What we want to do is, Multiply the "firstValue" and "secondValue" Variables, but as you can see, these two Variables are defined to work with different Data Types (the first is "float" type and the second "int" type). Also, the result of this operation must be stored in a "int" type Variable ("operationResult"). If we write the operation as such, we would have the following error message:
This type of message is shown because "we can not use a "float" type Variable in an operation where the expected result is an "int" type.
To solve these situations, it is necessary that all the terms used in our operations must be of the same type. Therefore, within the "Start" method is necessary to write the following:
void Start () { operationResult = (int)firstValue * secondValue; Debug.Log("Multiplication Result = " + operationResult); }
With “(int)firstValue” we are indicating that, although this variable is a "float" type, for this operation it should be considered as an "int" type. We call to this "Cast", "Type Casting" or just "Casting" (when explicitly informing the compiler to change an entity of one data type into another).
Note: To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted.
To know about "Casting", you can visit https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions .
Save the Script, switch to the Unity Editor Interface, and inside the “Inspector” window (remember first select “GameObject”) type the following:
- “5.5” in the “First Value” field.
- “10” in the “Second Value” field.
Run the scene, and the Unity's Console will show:
The result is "50", but "55" is the value we expected; this happens because when using "(int)firstValue", the "decimal" component of the value of our Variable is not taken into account (being "5.5" the original value, only the integer value "5" is taken into account and the decimal component ".5" is dismissed); since it is an operation of "int" type values, this is done as "5 * 10 = 50".
Note: Always take into account when performing a "Casting" that data loss might occur.
If the values are modify:
- “12” in the “First Value” field.
- “5” in the “Second Value” field.
Run the scene:
We can see that "Multiplication" Operation was successful (12 * 5 = 60)
If we modify the Class Members:
public float firstValue; public int secondValue; float operationResult;
And the “Start” Method is also modified:
void Start () { operationResult = firstValue * secondValue; Debug.Log("Multiplication Result = " + operationResult); }
We can see that no error message is displayed (this is because, "int" type value can be part of an operation with a "float" type result). The"conversion" from "int" to "float" type is "implicit". To know more about "implicit conversions" you can visit https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table .
Save the Script, switch to Unity and run the scene:
We can see that "Multiplication" Operation was successfully performed (12 * 5 = 60)
"Division" Operation.
Now we will continue with the "Division" Operation , for this, modify the Class Members as follows:
public int firstValue; public int secodValue; float operationResult;
Also modify the “Start” method:
void Start () { operationResult = 10.5f / 2; Debug.Log("Division Result = " + operationResult); }
As we can see, in this case we are not involving the "firstValue" and "secondValue" variables to carry out the "Division" Operation, we are only using numerical values; it should be noted that, as the result of this Operation is stored in the Variable "operationResult" ("float" type), the numerical values with "decimals" must include the suffix "f" to be taken as "float" type (thus "10.5f " is recognized as"float"), otherwise it would be taken as another Data Type that is not compatible with the "operationResult" variable (with the "integer"numerical values there is no problem, these are always recognized as "int" and there is no need for any modification).
Save the Script, switch to Unity and run the scene:
"Division" Operation was successfully done (10.5 / 2 = 5.25).
Modify again the Class Members:
public int firstValue; public int secondValue; int operationResult;
Also modify the “Start” method:
void Start () { operationResult = firstValue / secondValue; Debug.Log("Division Result = " + operationResult); }
Save the Script, switch to Unity, in the “Inspector” window (remember to select “GameObject”) type:
- “70” in the “First Value” field.
- “2” in the “Second Value” field.
Run the scene:
“Division” Operation was successfully performed (70 / 2 = 35).
"Remainder" Operation.
Finally, we are going to see the “Reminder” Operation. This is defined as obtaining the "Reminder" of a "Division".
It's Arithmetic Operator is "%" ("percentage" symbol).
It has many applications in programming. The most common example is "to recognize if a number is even or odd".
We know that a number is considered "even" if it is divisible by 2 and does not generate remainder (in other words, a division with a remainder equal to zero).
To perform this example, we will do the “Remainder” Operation as follows:
Modify the Class Members:
public int firstValue; public const int secondValue = 2; int operationResult;
Modify the “Start” method:
void Start () { operationResult = firstValue % secondValue; Debug.Log("The Remainder is = " + operationResult); }
Save the Script, switch to Unity, in the “Inspector” window let's type:
- “10” in the “First Value” field.
Run the scene.
The "Remainder" Operation was carried out correctly (10/2 = 5 and there is no remainder). We can say that "10" is an "even" number.
Let's try with a different number:
- “15” in the “First Value” field.
Run the scene.
The "Remainder" Operation was carried out correctly (15/2 = 7 and there is a remainder = 1). We can say that "15" is an "odd" number.
Note: Later, in the next tutorials, we will see more examples with the aforementioned Arithmetic Operators and introduce new ones.
If you want to know more about Arithmetic Operators, visit https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/#conditional-operator .
Exercises.
For getting a stronger knowledge about what you have already learned, it is necessary to practice it, so try to perform the following exercises:
- Use the “BasicOperations” Script you've created in this tutorial.
- Using “float” type Variables, write a code that convert from “meters (m)” to “feet (ft)”. Remember “ft = m * 3.28084”
- Using“int” type Variables, write a code that shows the “quotient” and the “remainder” of a Division.
This Unity Tutorial about “Access Modifiers”, “Arithmetic Operators” and their applications ends here. Join us in the next post where we will continue learning more about programming in C Sharp (C#) Language.
Remember, if you want to know more about this topic, you can always visit Unity's online user manual at https://docs.unity3d.com/Manual/ or, do not hesitate to contact us for any questions or advice by clicking “Here”