Introduction – ¿What is the origin of an object?

The origin of an object in Blender is the point in space that represents the whole object, for example if we want to say the exact position where the object is, we will use the position of the origin. Furthermore, transformations like position changes, rotations and scale will be calculated relative to the origin coordinate. The origin of a 3D model is a concept that is used throughout different design software, for example if we export our Blender model to Unity, the origin of the model that is defined in Blender will be the origin of the object in Unity.

For these reasons it is important to know how to set the origin of an object in Blender, placing it where we think it is more convenient.



All the IMPORTANT information is summarized in the following TUTORIAL FROM MY YOUTUBE CHANNEL


How to know where the origin of an object is located

The origin of an object in Blender is represented by a yellow dot, to see it we need to be in OBJECT MODE and select an object.
Below you can see a couple objects with their respective origins.

Fig. 1: Position of the origin in a default cube in Blender
Fig. 2: Position of the origin in a default toroid in Blender
Fig. 3: Position of the origin in a default cylinder in Blender

If you cannot see the origin even in OBJECT MODE maybe you have the “VIEWPORT OVERLAYS” disabled.



Working Modes – Object Mode and Edit Mode

Fig. 4: Working mode selector in Blender.

In Blender we can work in different modes, two of them in particular are the object mode and the edit mode, with the TAB key we can switch between both (if we have at least one object selected). In the object mode as its name indicates we will work with objects, that is, we will not take into account the geometry of the object itself, but its basic transformations, such as position, rotation and scale, and here the origin is important to represent the object in space. When we move, rotate or scale the object, we will be doing it in relation to its origin point.

In the object mode we can know the exact position of the origin point in the transformation panel (shortcut “N” if it is not visible), as we see in figure 5, in the tab Item, we can see the location of the origin, its rotation and its scale and of course we can manually enter values in these fields, positioning precisely an object or giving it a certain orientation or size.

Transformations tab in Blender, shows position, rotation and scale
Fig. 5: The exact position of the origin can be seen in the transformation tab in Blender.
Fig. 6: Edit Mode is selected.

On the other hand, when we work in Edit mode (figure 6), we get inside the object and we can see and modify its geometry, that is, the vertices, edges and faces that conform the mesh. In this mode we can create new faces and do all kind of geometrical transformations but the origin remains in the same location, unless we explicitly modify it.

Figure 7 shows all the vertices of the cylinder was selected and have been moved, the origin point however remains in place, if we compare it with the cylinder in figure 3.

Fig. 7: If we move one or more parts of the object in edit mode, its origin will remain at the same point.

How to modify the origin of an object in Blender using the 3D cursor

After understanding what the origin of the 3D object is and what it is used for, we will see how to modify the origin’s position to any point in space. To do this we will help us with the 3D Cursor.

First we will see how to position the 3D Cursor exactly where we want, for that we will see three examples, the first is to position the 3D Cursor in the center of a face, on a vertex or in the center of an edge.

Placing the 3D Cursor in the center of a face in Blender

Giving a certain object, we go to the edit mode and select a face from the mesh(with the faces mode, shortcut “3” or by selecting the vertices that define it). Once we have the face selected we use the shortcut “SHIFT+S” to open the SNAP menu, as we see in figure 8, this menu gives us many options, but the one that interests us at this moment is to move the 3D Cursor to the current selection, as we have the face selected, the result is that the 3D cursor is moved to the geometric center of the face, as we see in figure 9.

Fig. 8: We select one face of the model and using the shortcut SHIFT+S we access the Snap menu, choose “Selection Cursor”.
Fig. 9: El cursor 3D se ha movido al centro de la cara seleccionada.



Placing the 3D Cursor on a Vertex in Blender

If we repeat the process but this time having only one vertex selected, the 3D Cursor will be positioned on that vertex, see figure 11.

Fig. 10: We select a vertex of the model and using the shortcut SHIFT+S we access the Snap menu, choose “Cursor to Selection”.
Fig. 11: The 3D cursor has moved to the selected vertex.

Placing the 3D Cursor in the center of an edge in Blender

And if we do the process again but this time having an edge selected (two vertices), we see how the 3D Cursor moves to the center of that edge, see figure 13.

Fig. 12: We select an edge of the model and using the shortcut SHIFT+S we access the Snap menu, choose “Cursor to Selection”.
Fig. 13: The 3D cursor has moved to the center of the selected edge.

With practice, using one of these three techniques or a combination of them we will be able to position the 3D Cursor at any point of interest in the object or in the world.

How to move the origin to the 3D cursor in Blender

Fig. 14: How to move the origin to 3D cursor in Blender. In the object mode, right click on the model, then “Set Origin” and choose the option “Origin to 3D Cursor”.

Now that we have the 3D cursor placed in the position where we want to move the origin’s object we will proceed exiting the Edit Mode and entering the Object Mode, then right click on the object, go to the “Set Origin” option and choose the “Origin to 3D Cursor” option (figure 14), this will make the object’s origin move to the current position of the 3D Cursor.

As we can see in figure 15, the yellow dotthat represents the origin has been moved to the center of the edge where the 3D Cursor was located, from now on, the transformations made in object mode will be calculated with respect to that new origin, as we can see in figure 16, a rotation restricted to the X axis is made and the result is that the origin point remains fixed and the rest of the object rotates around it.

Fig. 15: The object’s origin has now been moved to the 3D cursor position.
Fig. 16: All transformations made in object mode will be calculated with respect to the point of origin.



Conclusion

The origin of an object defines the position of the object in the world.

The transformations that are made on an object, in general will be calculated with respect to the origin.

It is possible to set the origin of an object anywhere in space, but some locations will be more appropriate for a given object.

Introduction

In this article we will see how to solve the error “GUIText is obsolete” in Unity, an error that started to occur several versions ago because the GUIText programming class was replaced by another one and there are still many Unity packages using the previous version.

In the following video we see how I solve this error that appears when importing the Standard Assets package. This is an error that is simple to solve but it is important that you understand why it occurs and what to do, since the error can occur in countless cases, you will have to identify how to do it in your particular case.


Steps to solve “GUIText is obsolete” in Unity

1. Open all the scripts that contain this error. Help yourself with the error information in Unity’s console (clicking on the error will give you some extra information), the console will tell you the name of the script and the error line. If we double-click on the error, the script will open and the error line will be highlighted.

Fig. 1: This is what the error “GUIText is obsolete” looks like in the Unity console. Notice how the console reports the script name, the error line and suggest how to solve it.

2. It is necessary to replace the use of the “GUIText” fields by the “UnityEngine.UI.Text” class. That is, where we see that “GUIText” is used (case sensitive), delete it and write “UnityEngine.UI.Text” instead.

Fig. 2: The GUIText component is deprecated but in line 11 it is being used, resulting in a console error.
Fig. 3: “GUIText” is replaced by “UnityEngine.UI.Text”.

3. Save the script and verify in the console that the error disappears.

Optional: The prefix “UnityEngine.UI” can be included in the script header, that way we can refer to the component directly as “Text”. See lines 3 and 12 in figure 4.

Fig. 4: Implementation of the “UnityEngine.UI” namespace and replacement of “GUIText” with “Text”.

Introduction

The IF statement allows us to make a decision based on whether a condition is true or false.

The simple decision is to perform an action if the condition is true and otherwise do nothing. The double decision allows us to perform a second action if the condition is false.

In the following video you can see how to define an if statement in C# language with examples in Unity.

Script from the video

Below you can download the script to test the different ways to declare an If statement.

Ways to express the logical condition

The simplest way would be to use a boolean variable in the condition, but this is not the only way.

Logical Expression

Another way to do this is to create a logical expression using operators that determine whether the condition is true or false.

In the video I proposed the following example: “We can be hungry or not, if we are hungry there are two ways to eat, one is to be in the house and also have food or if not the other way is to be in a store and have money”.

With these assumptions we can create a logical expression that determines whether we eat or not. We can see it below.

weAreHungry && ( (insideHouse && weHaveFood) || (insideFoodStore && weHaveMoney) )

This expression will be true when we are in a position to eat and therefore we can use it as a condition of an if statement.

Method that returns a logical value

A method is a function that we can execute using its name, for more information see Modularization and Methods in Programming. If we have a method that returns a boolean value, its execution is equivalent to having e this value, so we can use this as a condition for an IF statement.

In the video I define a method called “ShouldWeEat()” that returns the value of the boolean expression.

Logical Expressions using other types of variables

Using the comparison operators (AND, OR, >, <, >=, <=, etc) we can create logical expressions using other types of variables such as integers, floats, characters, we can also compare strings. In the video I use as a condition the following expression:

money >= foodCost

If the money we have is greater than or equal to the cost of the food we will be able to buy it, otherwise we will not be able to.

Logical expression combining methods and operators

We can combine the two previous cases, if we have a method that returns an integer value for example, we can compare the execution of this method with another value and create a logical expression.

Introduction

In this article we will see how to play music and sound effects in Unity, making them play automatically when starting the game mode, but we will also see how to create a control script to play music or sounds in Unity through code.

To play audio clips in Unity we use a component called AudioSource, this component allows us to configure different parameters such as volume, make it play in loop, among others.

The AudioSource component by itself is not enough to listen to the audio in Unity, it is also necessary to have an AudioListener component in the scene, this component is usually assigned to the camera by default when creating a new scene, the AudioListener acts as the “ears” that hear the sound played by the AudioSources. We must make sure that there is only one AudioListener component in the scene, especially if we are using 3D sound effects, that is to say that we take into account the position from where the sound is originating, for example if a sound is produced to the right of the player’s perspective, that the sound is heard with greater volume in the speakers on the right.


How to play an AUDIO CLIP in Unity at startup

1. Create a GameObject and in the inspector assign the AudioSource component (Add Component button).

2. Configure the AudioSource component with the “Play On Awake” option activated and the rest of the parameters configured as you like (see below for the different options).

3. When you enter the game mode, the sound will start playing automatically with the parameters set.

How to play an AudioClip in Unity through code

1. Create a GameObject and in the inspector assign the AudioSource component (Add Component button). Deactivate the “Play on Awake” option and configure the other parameters as you wish.

2. Create a Script to control the start of the sound, the volume, the end, among other actions. Assign this Script to the same GameObject that has the AudioSource component.

3. In the script define a reference for the AudioSource object and find it in the Start method using GetComponent<>().

4. Define a public function to play the sound from any other script, within this function execute the instruction: “audioSource.Play()”.

5. Detect the proper event in which the sound should be played and execute the play function defined in the audio script.

AudioSource component setup

The AudioSource component has many adjustable parameters to achieve different results with our sounds. In the following image we see what the AudioSource component looks like in the inspector in Unity.

Fig. 1: Generic AudioSource component in Unity

To start with, you can manually assign the sound you want to play by dragging it to the AudioClip field. This can also be done from a script with the instruction “audioSource.clip=aClip;”, being “audioSource” the reference of the AudioSource component of the inspector and “aClip” a field that contains the reference of some sound.

Then we can mute the sound and adjust the volume. Enable the “Play On Awake” option so that the sound is played as soon as the GameObject enters the enabled state. The Loop option makes the sound play again when it is finished.

The Spatial Blend is a parameter that allows us to adjust if it is a background sound or a sound that depends on the distance between the AudioSource and the AudioListener. If we put the indicator in 3D, we will obtain a stereo sound whose volume and distribution in the headphones will depend on the position of the source. Within the 3D Sound Settings you can adjust parameters related to this.

Introduction

We’re going to see how to store bools in Unity using the PlayerPrefs class, then we’ll see how to load those bool values. This can be useful to save game states, for example if the player has already done some action.

How to save a bool with PlayerPrefs

PlayerPrefs doesn’t have a function to save logical values directly, so we’re going to save an integer that could be worth 0 or 1 depending on the state of the boolean variable, for this we use the static method “SetInt”, a function that needs us to give it two parameters.

The first parameter is a string with the name that will have this variable that we are going to store, this will allow that later we can recover it. The second parameter is the integer value that we want to store.

The instruction that will do the saving of the data in Unity would look like this:

PlayerPrefs.SetInt(“boolDataName”, boolData ? 1 : 0);

In this case we indicate the name of the data between quotes because it is a string, the second parameter we indicate it using the ternary operator “?:” that works as a simplified if statement, first we have the logical data we want to save, “boolData”, then the operator “?” and then the values it returns if boolData is true or false separated by “:”.

The expression “boolData ? 1 : 0” will result in 1 if boolData is true and 0 if boolData is false.

How to load a bool with PlayerPrefs

To load a bool into Unity using PlayerPrefs we have to remember that in the previous step we saved it as 0 if the variable is false or 1 if it’s true, so we retrieve the integer value using the “GetInt” function, a function that can be used in two different ways.

In the first form we give a parameter that is going to be the name of the data we want to retrieve, the name we gave it when we executed the “SetInt” function we saw before. We do it in the following way.

boolData =PlayerPrefs.GetInt(“boolDataName”)==1;

The execution of the static method “GetInt” of PlayerPrefs gives as a result an integer but by using the operator “==”, that compares if both expressions are equal, we get a logical result that we can assign to the “boolData” variable. If the stored integer is 1, boolData will be true, otherwise it will be false.

The second way is also to give it the name of the data that we use in the execution of “SetInt” but we also give a default value that will be used in case there is no data saved under that name, this is done in the following way.

boolData =PlayerPrefs.GetInt(“boolDataName”,0)==1;

Introduction

We’re going to see how to store floats in Unity using the PlayerPrefs class, then we’ll see how to load those float values.

This can be useful, for example, to save configuration parameters that has decimal values.

How to save a float with PlayerPrefs

To save a float in Unity using PlayerPrefs we’ll use the static method “SetFloat”, a function that needs two parameters.

The first parameter is a string with the name that will have this variable that we are going to store, this will allow that later we can recover it. The second parameter is the float value that we want to store.

The instruction that will do the saving of the data in Unity would look like this:

PlayerPrefs.SetFloat(“floatDataName”,floatNumber);

In this case we indicate the name of the data between quotes because it’s a string, the second parameter we indicate it using a float variable.

How to load a float with PlayerPrefs

To load a float into Unity using PlayerPrefs we’ll use the static “GetFloat” method, a function that can be used in two different ways.

In the first form we give a parameter that is going to be the name of the data we want to retrieve, the name we gave it when we executed the “SetFloat” function we saw before. We do it in the following way.

floatNumber=PlayerPrefs.GetString(“floatDataName”);

The execution of the static method “GetFloat” of PlayerPrefs results in a float value, that’s why it is assigned to the variable “floatNumber” in the above instruction.

The second way is also to give it the name of the data that we use in the execution of “SetFloat” but we also give a default value that will be used in case there is no data saved under that name, this is done in the following way.

floatNumber=PlayerPrefs. GetString(“floatDataName”,0f);

Introduction

In this article we see how to SAVE STRINGS in Unity using the PlayerPrefs class, to store information in the persisten memory, then we see how to load those strings from memory to recover the information. An application of this method could be for example save the player’s name in memory.

How to save a String with PlayerPrefs

To save a String in Unity using PlayerPrefs we’ll use the static method “SetString”, a function that needs two parameters.

The first parameter is a string with the name that will have this variable that we are going to store, this will allow that later we can recover it. The second parameter is the String data that we want to store.

The instruction that will do the saving of the data in Unity would look like this:

PlayerPrefs.SetString(“stringDataName”,stringData);

In this case we indicate the name of the data between quotes because it’s a string, the second parameter we indicate it using a string type object.

How to load a String with PlayerPrefs

To load a String into Unity using PlayerPrefs we’ll use the static “GetString” method, a function that can be used in two different ways.

In the first form we give a parameter that is going to be the name of the data we want to retrieve, the name we gave it when we executed the “SetString” function we saw before. We do it in the following way.

stringData=PlayerPrefs.GetString(“stringDataName”);

The execution of the static method “GetString” of PlayerPrefs results in a string data, that’s why it is assigned to the obhect “stringData” in the above instruction.

The second way is also to give it the name of the data that we use in the execution of “SetString” but we also give a default value that will be used in case there is no data saved under that name, this is done in the following way.

stringData=PlayerPrefs. GetString(“stringDataName”,””);

Introduction

We’re going to see how to save integer numbers in Unity using the PlayerPrefs class, then we’ll see how to load those numbers in Unity. This method will be useful for example to save the score in Unity, if that score is represented by an integer number of course.

How to save an integer with PlayerPrefs

To save an integer in Unity using PlayerPrefs we’ll use the static method “SetInt”, a function that needs two parameters.

The first parameter is a string with the name that will have this variable that we are going to store, this will allow that later we can recover it. The second parameter is the integer value that we want to store.

The instruction that will do the saving of the data in Unity would look like this:

PlayerPrefs.SetInt(“integerDataName”,integerNumber);

In this case we indicate the name of the data between quotes because it’s a string, the second parameter we indicate it using an int type variable.

How to load an integer with PlayerPrefs

To load an integer into Unity using PlayerPrefs we’ll use the static “GetInt” method, a function that can be used in two different ways.

In the first form we give a parameter that is going to be the name of the data we want to retrieve, the name we gave it when we executed the “SetInt” function we saw before. We do it in the following way.

integerNumber=PlayerPrefs.GetInt(“integerDataName”);

The execution of the static method “GetInt” of PlayerPrefs results in an integer, that’s why it is assigned to the variable “integerNumber” in the above instruction.

The second way is also to give it the name of the data that we use in the execution of “SetInt” but we also give a default value that will be used in case there is no data saved under that name, this is done in the following way.

integerNumber =PlayerPrefs.GetInt(“integerDataName”,0);

Description of the problem

A Canvas has been created with one or more buttons to perform an action, when running the game the buttons don’t work when you press them.

This is something that has happened to me on several occasions and can be due to several reasons.

Let’s assume you have a GameObject with the script with the button function defined as public, you have assigned it to the Button component of the Canvas and selected the appropriate function. If you haven’t done this and need help, I invite you to read this article on how to use Canvas buttons.



All the IMPORTANT information is summarized in the following TUTORIAL FROM MY YOUTUBE CHANNEL


Possible Solution #1: No EventSystem component in the hierarchy

When we create a Canvas, a GameObject called “EventSystem” is automatically created, as you can see in figure 1, this GameObject has some components associated to handle the input events (figure 2).

Fig. 1: GameObject EventSystem en la jerarquía.

Fig. 2: Componentes de EventSystem en el inspector.

If we accidentally delete the GameObject EventSystem, the mouse inputs are not detected and the Canvas buttons do not work.

To solve this we can create a second Canvas to make the EventSystem appear, then remove the second Canvas. Or we can simple create an EventSystem.

Possible Solution #2: Button configured as non-interactive

The Button component has a Boolean to disable it, as shown in figure 3 the “Interactable” box.

Fig. 3: The Interactable box is used to disable the button.



Possible Solution #3: Button is not a RayCast target

The button has an Image component for the background image and a Text component for the button text.

Both components have a box with the name “Raycast Target”, what it does is to enable the component to be detected by a ray tracing, the process by which it is detected that some element of the Canvas has been pressed.

In figures 3 and 4 we see the “Raycast Target” boxes. In a button if all the Raycast Target boxes are unchecked, it will not be possible to detect when clicking on those elements.

Fig. 4: Canvas image component.

Fig. 5: Canvas text component

To fix this problem, make sure that at least one Raycast Target box is enabled.

Introduction

In this article we see how to use buttons in Unity to make a certain action happen when you press those buttons. The actions that the button will execute must be defined inside a Script, it has to be a function with public visibility, so that we can assign that function to the On Click event of the button. By pressing a button we can make a simple action like exit the game or a set of actions as complex as we need.

All the IMPORTANT information is summarized in the following TUTORIAL FROM MY YOUTUBE CHANNEL


In case your buttons don’t work:

Graphic interface setup

Before we look at how to use Canvas buttons in Unity let’s create the minimum elements needed to be able to solve the problem.

Canvas

The Canvas is the object in which we can place elements belonging to the graphic interface. To create a Canvas we right click on the hierarchy, go to UI and then click on Canvas, as shown in figure 1.

Fig. 1: Creating a Canvas GameObject in Unity

Before going any further, I recommend to configure the Canvas climbing component according to your needs, this component is assigned to the Canvas and you can see it in the inspector.

In my case I will set the “UI Scale Mode” parameter to “Scale With Screen Size” and indicate a reference resolution of 1920×1080, as shown in figures 2 and 3.

Fig. 2: Canvas Scaler component of a Canvas type object

Fig. 3: Reference resolution for the Canvas climber

Button Object

Now inside the Canvas we create a Button. In the hierarchy, right click on the Canvas object, go to UI and choose the “Button” option, this will add a Button type object to the Canvas.

Fig. 4: Creation of a button object in Unity

Then I will create a panel that will have, as a child, a Text type object, both can be created from the same menu as shown in figure 4.

Fig. 5: The Canvas contains a button and a message. An empty GameObject is created to assign the script with the action.

Fig. 6: Elements of the graphic interface

Create an action for the button

As an example, the action will simply consist of making a sign appear saying that the button has been pressed.

For the button to be able to perform any action when pressed, we need to define it in a Script, so let’s create one by right clicking on the project folder, then go to Create and choose the option C# Script, as shown in figure 5.

Fig. 7: Creating a new script in Unity

We give it a name and then create an empty GameObject and assign the Script to it. In figure 5 you can see that I have created an empty GameObject called “ButtonTest”.

Fig. 8: We created a Script called ButtonTest to program the action of the button when pressed.

Fig. 9: Asignamos el Script al GameObject ButtonTest.

To describe all the actions that a button must do when pressed we create a method or public function within the Script, in figure 10 we see the function called “MyButtonFunction”.

It is VERY IMPORTANT that this function is declared as public, otherwise we cannot assign it to the button.

The function is responsible for incrementing a counter called “buttonPressedCounter” and then writing a message on the screen indicating how many times the button was pressed. The if I had to add it because when the counter is 1, the word “time” goes in singular.

You can try this same example for, remember to add the namespace that is in line 4, “UnityEngine.UI”, otherwise you will not be able to access the Text class.

Fig. 10: Code within the ButtonTest Script.

We go to the inspector and place the Canvas Text component in the script field.

Fig. 11: I assign the text requested by the script to the inspector.

Now we select the button and go to the Button component in the inspector, here we must click on the + button in the OnClick() panel, this will add a new action when an OnClick() event occurs, that is when the button is pressed.

Fig. 12: In the OnClick panel we click on the + button to add a new action.

Fig. 13: A field appears in which we can assign a GameObject.

As we see in figure 13, we have a field where we can assign a GameObject, here we drag from the hierarchy, the GameObject that has assigned the script with the action. As we see in figure 14, we have dragged the GameObject “ButtonTest”.

Fig. 14: We assign the GameObject containing the Script with the action we want the button to perform when pressed.

Then using the drop-down menu, which initially says “No Function”, we’ll first select the Script and then the public function we’ve created for the button, as shown in Figure 15.

Fig. 15: Using the drop-down menu, we choose the function that we want to be executed when the button is pressed.

Each time the button is pressed the poster changes showing the number of times it has been pressed.

Fig. 16: Every time the button is pressed the counter increases and the display changes.

Conclusion

We’ve seen how to use the Canvas buttons in unity. The action must be programmed within a script using a programming method and must be declared as public.

Then we must add a new field in the OnClick() panel of the Button component and assign the GameObject that the script has with the action.

Finally, using the drop-down menu in OnClick(), we must select the function we have defined in the script.

Introduction

In this article we are going to talk about what MonoBehaviour is in Unity, first a practical approach to know in general terms what it is and what functions it fulfils concretely, then we analyze MonoBehaviour from the programming perspective.

What do we need to know about MonoBehaviour to work at Unity?

When we created a new script in Unity, next to the name we gave it appears the word “MonoBehaviour”, this in simple terms is telling us that the script we made will behave like a MonoBehaviour.

This means that Unity will be in charge of executing certain functions automatically. To understand the concept of function in programming I invite you to read this article.

For example the “Start” function will be executed when the GameObject to which we assign our Script appears in the scene (when we start the game or when we instantiate it).

Another function that is automatically executed is “Update”, which is executed before showing each frame of the game, so it is a function that allows us to update the state of the game and produce the dynamic.

These two functions are defined by default when we create a new script in Unity, but there are also other functions that we can define and will be executed automatically at a certain point in the life time of a MonoBehaviour. You can read more about the Update function here.

A useful function that is not defined by default is the “FixedUpdate” function, which is similar to Update, but is executed equispaced in time with a default frequency of 20 milliseconds. This allows us to achieve changes in the game that should occur regularly over time, for example the movement of objects.

Other useful functions are “Awake”, “LateUpdate”, “OnDestroy”, “OnEnable”, “OnDisable”,

What is MonoBehaviour from a programming perspective?

Mono Behaviour is a “Programming Class”, this means that it is a set of variables, objects and functions that perform a certain function.

To know more about what is a class and object in programming you can consult this article.

When we create a new Script in Unity, what we do in the background is to create a new programming class that will have the same name that we gave the Script and that will also extend from MonoBehaviour, that is to say that it will inherit its behaviour from the MonoBehaviour class. That’s why the “Start”, “Update” or ”FixedUpdate” methods are automatically executed when the game starts running.

Introduction

In this article I am going to show the detailed process to access a variable defined in another script in Unity.

The main problem we are facing is the following, yesterday a person came in to ask how to read the defense value of an enemy from the player’s script, a while ago, just before you, someone came to ask how to make a control script access the total amount of coins collected to know if the objective has been achieved. And now you are here with your own project different from the others, with your own scripts to which you have given very particular names.

To solve this problem I will explain the solution USING GENERIC NAMES (such as “ScriptA” and “ScriptB“), you need to understand the procedure for this particular example and then you need to apply what you have understood to your own particular case, i.e. you need to determine who ScriptA and ScriptB are in your particular case.



All the IMPORTANT information is summarized in the following TUTORIAL FROM MY YOUTUBE CHANNEL


Step-by-step procedure to access a variable from another script in Unity

Step 1. Define which scripts are involved

This is a very important step for us to solve the naming problem, your scripts have a very particular name, different from the scripts of the other people who have entered in this article.

Please keep these two points in mind:

  • In this generic example we are going to use two scripts, their names will be “ScriptA” and “ScriptB“.
  • The variable we want to access is located in ScriptB and we are going to access this variable from ScriptA.



Step 2. Ensure that the variable is accessible from an external context

We must make sure that the variable we want to access (in ScriptB) is declared with public visibility, so that this variable can be accessed from an external context, for example from ScriptA.

For example, if the variable we want to access were of type int and its name were “exampleVariable“, in ScriptB we should define it as follows:

public int exampleVariable;

IF THE VARIABLE DOES NOT HAVE PUBLIC VISIBILITY IT CANNOT BE ACCESSED FROM OTHER SCRIPTS

Step 3. Define a data type that allows access to the script where the variable is located

Let’s remember that from ScriptA we want to access ScriptB, therefore inside ScriptA we have to define a ScriptB type variable, this variable will allow us to access from ScriptA to the variables and public functions defined in ScriptB.

We can define this variable as follows:

public ScriptB typeBVariable;



Step 4 (CRUCIAL). Initialize the above variable to point to the component we want to access

I can’t tell you how IMPORTANT this part is, not only to solve this particular problem of accessing a variable from another script, but for ANYTHING WE WANT TO DO IN UNITY. It is about being able to reference a precise object from a Script.

The point is that the variable that we defined in the previous step, if we do not initialize it, has a null value and if we try to use it in this state we will get a Null Reference Exception error in the console.

We have to make sure that the variable has in its interior the appropriate component to which we want to make reference, in this particular case the ScriptB type component.

This can be done in many ways, one of the simplest is to go to the Unity scene and in the ScriptA inspector drag the GameObject that has the ScriptB assigned to the ScriptB type field, in this way we place in the variable that component and we can use it inside the ScriptA.

Step 5. Use the ScriptB type variable to access the variable defined within that script

Once we completed the previous step we now have a ScriptB type variable that contains the reference of the ScriptB type component that is assigned in a GameObject in the Unity scene.

To access a variable defined in the other script we use that ScriptB type variable and with the dot operator we access the variable we are interested in. According to the example given in this step by step we would do it in the following way:

typeBVariable.exampleVariable

The previous expression is the variable that is defined in the other script, this variable can be used inside ScriptA or change its value if we wish.

Introduction

In this article we will see how to execute functions defined in one script from a second script. First we look at the generic procedure.

In the following video I explain how to call functions from another script.
All the information is presented to you as a generic example, two scripts, “ScriptA” and “ScriptB“, the function we want to call is defined inside ScriptA, so from ScriptB we are going to access to ScriptA.




Procedure

1. We start with 2 Scripts, “ScriptA” and “ScriptB”. In Script A is the function we want to call. In Script B we are going to call the function that is in ScriptA.

2. In ScriptA we make sure that the function is declared as public, otherwise we will not be able to access it from a context outside of ScriptA.

3. In ScriptB we declare a ScriptA type variable and we must find the reference of that object. This will depend on where we are programming, in the case of Unity we will do it in the Start method and with the instruction FindObjectOfType.

4. To call the function of ScriptA from ScriptB, we use the rererence we defined from A and with the dot operator we can access it and execute it inside ScriptB.

Introduction

In this article we will see how to tell if an integer is odd or even using programming. We solve the algorithm in C# language for Unity.

An even number is a number that is a multiple of 2, that is we can express that number as 2 multiplied by another number and the whole expression will be equivalent. An odd number is a number that is not a multiple of 2.

It can also be said that an even number is divisible by 2, meaning that when you divide the number by 2 the remainder of the division is 0, whereas division between an odd number and 2 will always have remainder 1. We can use this fact to create an algorithm that checks whether a number is odd or even.

Prepare the scene for testing

To test the code to verify if an integer is odd or even we’ll create a script with any name, in my case I used “EvenOrOdd”, then we create an empty GameObject in the hierarchy (figure 1) and assign that script in the inspector (figure 2), that way when we enter the game mode the script will run and we can test the code.

Fig. 1: Creating an Empty GameObject in the hierarchy in Unity
Fig. 2: Assigning the script to the GameObject

Module Operator

The module operator allows us to know how much the rest is worth when making a division.

Let’s consider a division operation between two integers, for example 5 divided by 3, the integer result of this division is 1 and the rest of the division is 2, we can see that: 3 x 1 + 2 = 5.

Then, taking into account what we said in the introduction about even numbers and divisibility by 2, if we apply the operation module 2 to any number and the result is equal to 0, we can say that the number is divisible by 2 and consequently is an even number. If the result is not 0, then the number is odd.

The programming of this algorithm can be seen below in figure 3, in line 10 a random number between 0 and 100 is generated, then in line 12 we make this check if the module 2 of that number is equal to 0 and we assign that logical result to the logic variable “esPar”. Finally, using the if statement, we check if the condition is true or false and print a message according to each case.

Fig. 3: Algorithm to know if an integer is odd or even in C#, Unity.

When entering the game mode, the code defined in the Start method is executed, in figures 4 and 5 you can see two different executions of this algorithm, one for an even number and another for an odd number.

Fig. 4: Console message indicating that the generated number is even.
Fig. 5: Console message indicating that the generated number is odd.

Introduction

In this article we analyze an experiment to understand what are the differences between Update and FixedUpdate in Unity. To see these differences I set up a simple Unity scene with two cubes and some programming scripts, you will find the Unity Packge for download in this article.

Download Unity Package

Below you can download a Unity package that you can import in your Unity project and see how two objects behave with a translation applied in the Update method in one case and in the FixedUpdate method in the other.

In the following video we see a prototype made in Unity to point the differences between the Update and FixedUpdate functions in Unity.


What are the Update and FixedUpdate methods

To begin with, the Update and FixedUpdate methods are functions that belong to the MonoBehaviour class and will be executed automatically and cyclically when we place those Scripts in the hierarchy.

Summary of the differences between Update and FixedUpdate in Unity

1. The amount of Update executions per second is variable, while the amount of FixedUpdate executions per second is fixed.

2. In general, you have no control over the execution of the update method, it will depend on the performance of the computer in which the game is running. For the FixedUpdate function we can change the Fixed Time Step, by default is 0.02 seconds (20 milliseconds), so we know exactly how many times this function is executed.

3. Both functions are used to make changes in time, from the above it can be concluded that the Update method is more convenient for the logical part and FixedUpdate for the physical part, movements and animations, i.e. actions that must change regularly in time.

How to see the differences between Update and FixedUpdate using the package to download

When you import the package you will have a folder that contains all the necessary files, what you have to do is open the scene that is inside the folder, called “UpdateFixedUpdate”.

Inside the scene we have a frame per second counter to know the refresh rate of the game at all times.

We have two Cubes called Update and FixedUpdate, both have assigned a script called “UpdateFixedUpdate” in which is defined a speed for the cube movement and a logical variable that will determine if the cube movement is done in the Update function or in the FixedUpdate function.

Then there is another GameObject called Saturation that has assigned a Script called “CreateObjectsForever”, when this Script is activated it will start instantiating cubes as children of the Saturation GameObject in an uninterrupted way, which will cause little by little a processing overload and with a little analysis it will allow us to understand the differences between Update and FixedUpdate in Unity.

Procedure for Analysis

First Test without Overload

Initially we make sure that the GameObject Saturation is disabled or your “CreateObjectsForever” script is disabled, so that initially no saturation occurs in the game.

We make sure that both objects have the same speed in their Script UpdateFixedUpdate and that in the Update object the box “Use Fixed Update” is unchecked, while in the FixedUpdate object, that box is checked.

We enter the game mode and observe how the cubes behave. In my case we can see that the cube that moves using the Update method moves faster than the cube that moves in the FixedUpdate method. The cube that moves with Update does so at more than twice the speed and sometimes moves faster and sometimes slower, while the other cube moves regularly over time.

Second Test with Overload

Now we activate the Saturation object (or its script), to activate the instantiation of the objects.

When entering the Game Mode, you will notice that the game’s FPS begin to gradually decrease. This change can be even more drastic if we select the Saturation object in the hierarchy and if we are looking at it closely in the Editor tab. But the most important thing that we notice is that the speed of the cube that moves with Update starts to decrease, the more the overload, the slower the cube moves, until in a moment it is overtaken by the cube that moves with FixedUpdate.

This indicates that the higher the processing saturation, the Update function is executed less times per second, while the FixedUpdate function is executed regularly in time and, even though the game starts to have lag, the movements will be proportional.

Exit mobile version
Secured By miniOrange