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.

error GUIText is obsolete in unity console, double click to open script with error
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.

Introduction

In this article we see how to export a game from Unity to Android and look at some of the problems we may encounter in the process and how to fix them.

In the following link you can see the basic setup to export a Unity project to Android, creating a 32 and 64 bits version that can be uploaded to Google Play, I also show how I solved an annoying error with the message “IL2CPP.exe did not run properly”.


Download Unity and the Android package

When installing Unity we must make sure we also download the Android package, so if you haven’t done this or don’t remember it, it’s a good opportunity to download the latest version of Unity along with all the necessary packages.

In particular I like to see all available versions, so in Google I usually search with the term “unity version download”, which leads me to the page with all versions (first page in figure 1).

Fig. 1: We look for the page that contains all versions of Unity.

From there we will access a page like the one shown in figure 2, in my case, because my connection is somewhat unstable, I download Unity using torrent.

Fig. 2: In the list we have several options to download Unity.

Fig. 3: In my case I download the latest version by torrent.

Clicking the highlighted option in Figure 3 automatically downloads a torrent file.

Fig. 4: Downloading the torrent file and open it.

We will need to download the Unity editor and the Android Build Support, in figure 5 are selected the necessary packages.

Fig. 5: In the torrent window we choose the necessary files, in this case we need at least the two selected files.

Configure Android SDK y JDK

To export our Unity games to Android we need to use some external tools, the Android Software Development Kit and the Java Development Kit.

If you don’t have these two kits installed, I’ll show you some screenshots and download links later, for now let’s assume they are installed and move on to the Unity part.

Enter Edit > Preferences and go to the External Tools part, there must be fields to indicate the path of the Android SDK and JDK, as seen at the bottom of figure 6.

Fig. 6: In the preferences window we go to the External Tools part.

By clicking on Browse, we indicate the path of these two development kits. The default installation path of the Android SDK is shown in figure 7, please note that the AppData folder could be hidden.

The path of the JDK is shown in Figure 8, inside program files, Java.

Fig. 7: This is the location of the Android SDK, if you do not find this on your disc read below.

Fig. 8: This is the location of the JDK, if you do not find this on your disk read below.

Configure Unity for the Android Platform

Now we must tell Unity the type of platform we want to export to, in this case Android. To do this, go to File > Build Settings and a window like the one shown in figure 9 will be displayed.

Fig. 9: In the Build Settings tab we select the Android platform and put Switch Platform.

In this window we select the option Android and click on Switch Platform, with this Unity makes a background work and after a moment the project is already adapted to work with Android.

Before creating a compilation we need to set up a few more things.

Go to the project’s Player window, in the Edit > Project Settings > Player tab.

Fig. 10: Let’s go to Edit > Project Settings > Player, to make the necessary settings to export from Unity to Android.

Here we can enter our brand, the name of the game, icons, Google Play keys, among other things.

Fig. 11: Here we can put the name of our Studio and the name of the Game.

At this time we are interested in creating an APK version of the game to test on an Android device, so let’s go directly to the “Other Settings” part and in the field called “Package Name” we have to indicate an identification name that will have in Android.

This is mostly to differentiate our application from all others in existence. The structure of this name should be like this: “com.Company.ProductName”.

For example if GameDevTraum creates a game called “Maze”, the name of the package could be: com.gamedevtraum.maze. It does not need to match a web domain.

In figure 13 we see that I simply used the name: com.mycompany.proyecto1 and this already allowed me to create an Android build.

Fig. 12: A package name is required in order to compile for Android.

Fig. 13: Example of package name.

This package name will appear for example in the Android folder of our device.

Fig. 14: The package name is the name of the application installation folder.

With this we can basically export our game from Unity to Android, go back to the Build Settings window and click on Build and Run.

Fig. 15: With this we are ready to compile, in the Build Settings window we click on Build and Run.

Here we must enter a location and a name for the final file. When you hit Save, the compilation process begins and when it finishes, you have an .apk file that you can install on an API-compatible Android device.

Fig. 16: You will be asked to select a location and a name for the file exported from Unity to Android.

Fig. 17: When the compilation process is finished we will have an .apk file to install in Android.

Unknown sources

By default Android devices reject applications that come from unknown sources, i.e. that are not signed and approved.

To test our game we must allow this type of application to be installed. We can do it from the Android configuration, in my case from “Screen Lock and Security”. You can also do it from the installer and indicate that it is allowed only for that particular installation, that way we will keep rejecting applications from unknown sources.

Fig. 18: At this point, to install the game in an Android device we must accept the unknown sources, this can be done directly from the installer.

We installed the application on our Android and can now test it. In my case I used directly the Android Studio emulator, as you can see in figure 19.

Fig. 19: Testing the application from the Android Studio emulator

Development Kits Downloads

Android SDK

On the Android Studio download page you can get the Android SDK.

There are two ways to install it, one is to download and install the complete Android Studio program. The other way is to download only the Android SDK, scrolling on the same page you will find the downloads. Figures 20 and 21.

Fig. 20: A quick way to get the Android SDK is to directly install Android Studio.

Fig. 21: The Android SDK can also be downloaded individually.

Java Development Kit (JDK)

You can download this JDK from the Java Development Kit download page. In figure 22 we see the download page, we must accept the license terms and then choose the appropriate package for our operating system.

Fig. 22: Java Development Kit (JDK) download page

Environment Variables

Some years ago it was necessary to manually add some Environment variables to the operating system in order to create Android applications. I think this is no longer necessary, but anyway if all the above has not worked I leave you some information about these environment variables to guide you and you can find a solution.

In the following video you can see how to check if you already have this environment variable defined and how to define it if not.

ADD Environment Variables to the system
👉

If we write “Environment Variables” in the Windows search bar, the option “Edit system environment variables” appears, as shown in figure 23.

When entering this option, the system properties window appears and there we have a button to view and edit the System Environment Variables.

In my case it was not necessary to add them manually so I will not go further than this, with this base you can search the web for some solution to the particular problem you have.

Fig. 23: Some time ago it was necessary to create some environment variables in order to create Android applications.

Fig. 24: Location of environment variables to be added or modified

Exit mobile version
Secured By miniOrange