Javatpoint Logo
Javatpoint Logo

Variables and Functions

GameObjects have components that make them behave in a certain way. When we refer to components, we are referring to the available functions of a GameObject, for example, the human body has many functions, such as moving, eating, talking, and observing. Now let's say that we want the human body to move faster. That means movement function is linked to that action. So to make our human body to move faster, we would need to create a script that had access to the movement component, and then we would use that to make the body move faster.

Just like in real life, different GameObjects can also have different components; for example, the camera component can only be accessed from a camera. Many components already exist that were created by Unity's programmers, but we can also create our own components.

This means that all the properties that we see in the Inspector tab are just variables of some type. They simply store data that will be used by some function.

Public Variables

If you put the public at the beginning of a variable statement means that the variable will be visible and accessible. It will be visible as a property in the Inspector panel so that you can change the value stored in the variable.

Example:

Private Variables

Not all the variables needed to be public. If there is no need for a variable to be changed in the Inspector panel or be accessed from other scripts.

Example:

Example

Let's create a script with the name myTest.cs that has one int variable:

Now create a GameObject (from the top menu GameObject-> Create Empty) and add the myTest.cs script file to the GameObject (in the Inspector panel of newly created GameObject). Now it will look in the GameObject's Inspector:

Variables and Functions in Unity

Here, we can see that it has myTest.cs script file, but it does not have our num variable at all.

Let's modify our script by adding a new variable, but this time with the public prefix. In a programming language, the public means that the value can be seen by other classes too. In Unity, the public also means that the variable will be shown in the Inspector.

The modified myTest.cs script is:

Just like other components often have properties that are editable in the Inspector panel, we can allow values in our script to be edited from the Inspector too.

Variables and Functions in Unity

Enter the value for variable Name and then press play. You will see that the message includes the text you entered.

Variables and Functions in Unity

Hence, in Unity, you must declare a variable as public to see it in the Inspector.






Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA