Introduction

In this article we see what MODULARIZATION is in programming and why it is important. We will also see examples of applications in C# language in Unity.

What is MODULARIZATION in Programming and what is it for?

The word modularization comes from module, whose textual definition is: ” each of a set of standardized parts or independent units that can be used to construct a more complex structure, such as an item of furniture or a building”.

Modularization is the process by which we select and group programming instructions that fulfill a specific function.

Creating modules is important because of the following:

Suppose we have a problem, as complex as you want, and the solution is to execute as many programming instructions as you need. Using programming modules, we can build a solution that can be executed using only one instruction. This instruction will go to the content of the module, execute each of its instructions and when the program ends, it will return to the point where the module was called.

The advantage of this is that we create the module only once and then we can reuse it as many times as necessary and from any part of the code, in addition, we no longer need to think about the internal functioning of the module, we use it as a whole that we know will perform a certain function. In other words, we increase the degree of abstraction of our code.

code reuse using programming modules
Fig. 1: On the left is a list of instructions with repeated code. With a module we can reuse the code and get something more compact as seen on the right.



Characteristics of the modules in programming

Regarding Functionality

A module should have a specific function and not go beyond its responsibilities. For example, if we have a module that calculates the product of two numbers and returns the result, it would not be appropriate for it to also print messages on the screen or do anything else that goes beyond its purpose.

Regarding Identification

The modules have an identification name that allows us to execute them, it is recommended that we choose this name so that it is as representative as possible of the function it performs, that way it is more intuitive when using it.

Input parameters

The modules can accept input data that will be used by your internal instructions to perform the function.

When defining a module, you should indicate all the parameters it requires and what kind of data it is. At the moment of executing the module, all the necessary parameters should be added, in the established order and they should be of the right type.

Output parameter

The modules can return a data as a result of its execution.

When defining a method, the type of data it returns must be indicated and the last instruction of the module must be the return of that data. When the module is executed, it must be taken into account that the call to that method implies a data as a result, so we must see what is done with that data, we can, for example, assign it to a variable or an object.

Visibility

When we define a module we can give it different types of visibility that will limit the access to them, for example the modules that belong to the internal functioning of a programming class are usually defined as private, so they cannot be accessed from a context external to that class.

In C# we have three types of visibility, public, private and protected.

Public visibility implies that the function can be accessed from any context, i.e. we can for example execute the function from another programming script.

Private visibility implies in simple terms that the module can only be accessed from the programming script itself.

Protected visibility is used when we have class inheritance and serves to allow subclasses to access these modules, but not external classes.

Fig. 2: This picture summarizes the main features of a programming module.



Definition of a programming module in C#

To create a module in C# we are going to use the declaration syntax of a programming method, which consists in first indicating the visibility type, then the return data type (or write “void” if it does not return data), then the module identification name (it is recommended to start with capital letters and use camel case), then between parentheses all the data required by the method including the data type and finally the keys are opened and closed. All the instructions of the module will be inside those keys.

In figure 3 we can see the syntax of several generic modules, all of them with public visibility (to make it private we must use the word “private”).

On the top left we have a module that does not return data (void is used in the definition) and neither requires input parameters (it opens and closes parenthesis).

At the top right we have a method that does not return data and requires a number N of parameters (we see that in brackets are included the data separated by comma). The parameter p1 could be for example “bool b1” indicating that it is a bool type and its name is “b1”. So, inside the module we can use b1 knowing that it is the information that comes from the outside.

Fig. 3: Generic examples of the syntax of the modules in programming

In figure 3, at the bottom left we have a method that doesn’t require input parameters but does return a data, since next to public it says “datoX”. Instead of datoX we have to put a data type, like a primitive variable or an object, for example “int” indicates that the module returns an integer value, while “Vector3” indicates that the module is going to return an object of the Vector3 class. Note that at the end of the method a value of name X is returned, this value must be of the same type that was declared in the method.

In figure 3, at the bottom right we have a method that requires parameters and returns a data.

Example of a module in C#: Calculating the area of a circle with a certain radius

We are going to design a module that is in charge of calculating the area of a circle. This module will receive as parameter a real value that represents the radius of the circle and will return a real value that will be the value of the area of a circle with that radius.

Pseudocode

Function AreaOfCircleWithRadius (FLOAT radius)
– BEGIN
– – Float area <- PI * radius * radius
– – RETURN area
– END

Implementation with C#

The syntax in C# language of a method based on the above pseudocode is as follows.

Module Definition

private float AreaOfCircleWithRadius(float radius){
      float area = Mathf.PI * radius * radius;
      return area;
}

Of course this is not the only option, you can also do:

private float AreaOfCircleWithRadius(float radius){
      return Mathf.PI * radius * radius;
}

Calling the module

Then we can for example make use of this programming module from Unity’s Start method in the following way:

void Start(){
      float r = 5;
      float a=AreaOfCircleWithRadius(r);
      Debug.Log("The area of a circle with radius: "+r+" is: "+a+".");
}

Introduction

In this article I present a solution to automatically create cables that hang from two or more points. The system allows us to modify the thickness of the cable, the curvature and more parameters to achieve the result we want.

The wire is drawn using Unity’s Line Renderer component so it is generated procedurally using mathematical expressions.

Unity Package

The solution consists of a Unity package that you can import into your project, this will create a new folder in your project with the Assets that come in the package.

How the Wiring System Works

Figure 1 shows the Assets that come in the package. In the scene you can see a power line that I generated using the wiring system.

To start using the system we can drag the prefabricated “GDT Wire Container” into the hierarchy (blue cube in figure 1). If you can’t create a new Empty GameObject and assign it the “GDTWiringSystem” script this will automatically generate everything needed for the system to work.

Fig. 1: The download package contains these assets.

The object assigned to the “GDTWiringSystem” script will be the one to draw the cable and its children will be the points from which the cable will be hung.

In figure 2 we see the “GDTWiringSystem” component, here is all that is needed to shape the wiring.

Fig. 2: In the inspector we can modify the wiring parameters.

Adding new points for the cable

To create a new holding point for the cable, simply right click on the container object and then click on Create Empty, as shown in Figure 3. This will create a new child and the script will automatically name it.

I do not recommend creating new children by duplicating existing ones, as this produces internal errors.

Fig. 3: To add a new point to the wiring you have to create a new child in the GameObject container.

Fig. 4: A new holding point is created for the cable.

In figure 4 we see how when creating a new point, a new section of cable appears.

Wire loops

If we want to generate a cable with its ends connected we can activate the option “loopWire”, this will generate a new stretch of cable that joins the last point with the first one.

Fig. 5: The loopWire option makes the last point of the cable connect to the first point.

In figure 6 we see that the cable has been closed.

Fig. 6: With the loopWire option we see that the cable forms a closed curve.

Wire Smoothness

The subdivision parameter allows us to choose the amount of segments that will be between two points of the cable, initially it is 1, which implies that the points of the cable are joined with straight lines, for the cable to have curvature we must choose a subdivision parameter greater than 1.

The larger the subdivisions, the smoother the cable curvature. The maximum range is set to 15 but it can be increased by opening the script and modifying the “[Range(1,15)]” instruction with the required value.

Fig. 7: If we increase the subdivisions we will get smoother curves.

Cable Curvature

To modify the concavity of the cable, that is to say how intense its curvature is, we have the Sliders inside the “Curvature Parameters” vector, as we see in figure 8.

The default range of these sliders is -3 to 3, but if necessary you can modify it from the script in the “[Range(-3f,3f)]” instruction by typing the required value.

Fig. 8: The bending parameters allow us to adjust the concavity of each cable section.

Animation

In case you need to animate the cable, I added a bool called “isAnimatedWire”, when you activate it the cable will be drawn in each FixedUpdate execution that by default is executed every 20 mili seconds.

Result

Using this solution we can automatically draw cables suspended from two or more points. We can add as many points as we want and modify the curvature of each section individually.

The cable is drawn with the LineRenderer component and using mathematical expressions.

Fig. 9: As the subdivisions are increased, the curvature of the cable can be seen.

Introduction

In this article, we’ll explore several methods to calculate distances between objects in Unity—a fundamental skill for game development. Whether you need to check how far a character is from a key location, trigger events when objects approach each other, or create proximity-based mechanics, understanding these techniques is essential. We’ll cover both simple solutions and optimized approaches, complete with practical code examples.

For a visual breakdown of this subject, you may find my video discussion helpful:




Setting up the scene

Let’s make a very simple scene that will have two spheres with 3D texts to indicate the number of the sphere and the distance between them.

Fig. 1: These are the GameObjects in the scene hierarchy.

Fig. 2: Script that will take care of the calculations.

The camera will have assigned the Script named “Distances” which is the one that will calculate the distance and write the values on the screen. As an extra, we’ll add a Line Renderer component to draw a line from one object to another.

In figure 2, we see that there are fields for both objects and for the distance indicator. We also have an enum that allows us to choose if we want to calculate the distance in space or projected in a certain plain.

Fig. 3: This is how the scene looks with the objects.

Preparing the Script

The Script that solves the calculations calls “Distances” (complete Script at the end of the article), in the following figure, we can see the fields defined in this Script and the Start method.

Fig. 4: Fields and Script Start method for calculating the distance between two GameObjects.

We have serialized fields (appear in the inspector) to assign the two spheres from the hierarchy, a TextMesh component for the distance indicator and the enum that allows us to choose which distance we want to measure.

Fig. 5: Code of the Update method.

In the Start method, we find the reference of the Line Renderer assigned to the GameObject camera.

In the Update method, we are going to do the calculations, for this, we define two methods “CalculateDistanceInSpace” and “CalculateDistanceXYPlane”, this last one takes into account only the X and Y components of the objects as if the objects were projected in the XY plane, this is useful when we use the orthographic view. In figure 6 we can see these methods.

Article about “Methods” in programming

Fig. 6: Methods for calculating distances in space and in the plane.



Calculate distance between two objects in space – Vector3

Let’s start by looking at how to calculate the distance between two objects in space, i.e. considering the three dimensions of the scene.

The CalculateDistanceInSpace method in Figure 6 takes care of this. As you can see, the “Distance” function of the Vector3 class is used and we use the positions of the objects as parameters, this method will return the distance between the two vectors.

https://gamedevtraum.com/wp-content/uploads/es/desarrollo-de-videojuegos/tutoriales-y-soluciones-para-el-motor-unity/calcular-distancia-entre-dos-objetos/distancia-entre-dos-objetos-espacio-unity.mp4
Video 1: Distance between two objects in space.

Calculate distance between two objects in the plane – Vector2

If we are working in 2D or if we are interested in knowing the distance between two objects projected on a plane, we can calculate this distance using only two dimensions of the scene.

The CalculateDistanceInXYPlane method in Figure 6 takes care of this. As you can see, the Distance method of the Vector2 class is used, two vectors are built using only the x and y components of the position of the objects and they are passed as parameters to the Distance method of Vector2.

https://gamedevtraum.com/wp-content/uploads/es/desarrollo-de-videojuegos/tutoriales-y-soluciones-para-el-motor-unity/calcular-distancia-entre-dos-objetos/distancia-entre-dos-objetos-plano-unity.mp4
Video 2: Distance between two objects in the plane.

In the following video, we can see the difference between these two ways of calculating distances between objects in Unity.

https://gamedevtraum.com/wp-content/uploads/es/desarrollo-de-videojuegos/tutoriales-y-soluciones-para-el-motor-unity/calcular-distancia-entre-dos-objetos/distancia-entre-dos-objetos-unity.mp4
Video 3: Comparison of the distance between two objects in the plane and in the space.

Conclusion

We have seen how to use the classes Vector3 and Vector2 to calculate distances between objects in space and in the plane respectively.

In general Unity works in 3D space, therefore to measure distances in two dimensions it is necessary to project the points in some plane. We have to take into account that there are several planes that we can use, in this case, we used the XY plane, but there is also the XZ, the YZ plane and we can even define a plane oriented in any direction.

Appendix

Here you can see the complete script that calculates the distance between two objects in Unity.

Fig. 7: Script Distances.

Introduction

In this article we will see how to define the factorial operation of a number, calculations and properties. It is a useful operation that is commonly applied in the development in series of functions.

Definition of the Factorial Function

This operation is symbolized with the admiration symbol in front of the number to apply it, the factorial of 3 is symbolized !3.

Applies to natural numbers including 0. This means that we cannot calculate the factorial of a negative number or a number with decimals, see numerical sets for more information.

The factorial of 0 is equal to 1, that is !0 = 1.

The factorial is equal to that number multiplied by the factorial of the previous number. We can continue applying this property until we reach the factorial of 0.

We can represent this operation using the product notation, in the following way:

(1)  

One way to calculate the factorial in programming is to use this producer notation and solve it in a loop, as we saw in the article about summation and product notation.

Examples of use of the factorial

Power Series Expansion

An example of the use of this operation is in the Taylor Series or power series expansion, which consists of a series of infinite terms to which we can adjust the coefficients to approximate a function that we want and that meets the minimum conditions for this to be possible.

Fig. 1: Desarrollo en Serie de Taylor de una función f(x). Aplicación del factorial.

Notice in figure 1 in the divisor of the summation term there is a number ranging from 0 to infinity and the factorial is applied to it.

The series approach is very useful because it allows us to find numerical solutions to certain problems, instead of evaluating a complicated function or even an unknown function, we evaluate polynomials.

Combination

The combination is useful for various applications, for example to find out how many possible combinations exist between certain quantities. You use factorials in the definition of combinatorial numbers:

   

Conclusion

We have seen the factorial operation that is symbolized with the exclamation point and is defined as a multiplication of a number by all the natural numbers before it.

The factorial applies to natural numbers including 0.

The factorial of 0 is equal to 1, henceforth, the factorial of a number is defined as the product of all natural numbers up to that number.

Introduction

In this article I share a mix of environmental instrumental rock that I prepared to listen to when I am writing articles or programming.

For this mix I have selected 16 songs from the YouTube library. The mood of the songs at times is calm, other times more moved, without becoming extreme, which allows me to isolate myself from the environment without distracting me.

Instrumental Rock Mix

Without further ado here you can listen to the instrumental rock mix, I hope you like it 😀

Names of the Songs and Artists by order of appearance

00:00 – 03:32 Without A Sound – Letter Box
03:32 – 06:15 Open Highway – Silent Partner
06:15 – 09:53 Lay It Down – Silent Partner
09:53 – 14:20 Don’t Look – Silent Partner
14:20 – 16:59 Silver – Riot
16:59 – 23:22 1973 – Bruno E.
23:22 – 26:05 Double You – The Mini Vandals
26:05 – 30:28 Town of 24 Bars – Unicorn Heads
30:28 – 34:34 Remembering Her Face – Silent Partner
34:34 – 38:04 Promises – Letter Box
38:04 – 41:03 In the Shadows – Ethan Meixsell
41:03 – 46:09 To the Sun and Back – TrackTribe
46:09 – 48:55 The Big Conference – DJ Williams
48:55 – 53:35 Heading West – Audionautix
53:35 – 57:45 We Could Reach – Freedom Trail Studio
57:45 Texas Napkin – Freedom Trail Studio

Introduction

In this article there are decorative 3D models to download and use in your projects at Unity.

For each model there are representative images and a brief description of the model, indicating data such as the topology and the quantity of materials.

The models are in .fbx format and can be imported directly into the Unity engine.

You can use these models to build prototypes quickly. I hope you find them useful.

Frames

This set of paintings is prepared for you to import it into Unity and you can put any image you want, as long as they are square or aspect ratio 16:9 or 9:16.

It also has several textures for the frames.

Vertices: 36 Faces:  27

Table

A simple table for 6 people with PBR textures.

Vertices: 184 Faces: 186

Chair

A simple chair with PBR textures.

Vertices: 132 Faces: 88

Shelf – 4 Shelves

Shelf model with 4 shelves. In the download are included the 3 textures that are observed in the image.

Vertices: 72 Faces: 55

Shelf – 3 Shelves and drawers

Shelf model with 3 shelves and a space for drawers or doors. This space is not functional, i.e. the drawers cannot be opened, it is only decorative. In the download come the two textures that are seen in the image.

Vertices: 68 Faces: 56

Chess Set

Set of chess pieces and table. Each piece is an individual model and can be given movement.

Vertices: 4169 Faces: 4102

Candlestick

Vertices: 256 Faces: 231

Introduction

In this article there are Seamless PBR Textures of floors to download and apply to your 3D models.

A Seamless texture is a texture with horizontal and vertical symmetry in such a way that it can be placed one after the other and the result is a continuous texture.

The term PBR is “physics-based rendering” and means that these textures are prepared to behave appropriately with light sources. These particular textures are adapted to the Unity engine (Metallic Workflow).

For each texture there are representative images and a brief description, indicating data such as the resolution.

The textures have several maps each and are in PNG format.

You can use these textures to apply to your 3D models in Unity and build prototypes quickly. I hope you find them useful.

Brick floor

Resolution: 1024 x 1024 – Maps: 3 – Format: PNG

Introduction

In this article there are 3D models of kitchen elements to download and use in your projects at Unity.

For each model there are representative images rendered in Blender 2.8 and a brief description of the model, indicating topology data and materials.

The models are in .fbx format and can be imported directly into the Unity engine.

You can use these models to build prototypes quickly. I hope you find them useful.

Pot

Vertices: 146 – Faces: 144

Gas Range

Vertices: 663 – Faces:  527

Introduction

In this section you can find 3D models of tools to download and directly import into Unity, ready to use in your projects.

Depending on the model, some have textures or another particular feature.

The models are in .fbx format and can be imported directly into the Unity engine.

You can use these models to build prototypes quickly. I hope you find them useful.

Miscellaneous Tools

This is a set with several small hand tools, has textures and is intended to function as decoration.

Vertices: 379 – Faces:  375 – Textures: Yes

Crowbar

Vertices: 108 – Faces:  107 – Textures: Yes

Axe

Vertices: 112 – Faces: 108 – Textures: Yes

Shovel

Vertices: 224 – Faces: 208 – Textures: No

Hoe

Vertices: 116 – Faces: 106 – Textures: Yes

Introduction

In this section you can find 3D models of weapons to download and directly import into Unity, ready to use in your projects.

Depending on the model, some have textures or another particular feature.

The models are in .fbx format and can be imported directly into the Unity engine.

You can use these models to build prototypes quickly. I hope you find them useful.

Knife

A simple knife to use in a hand or throw. The model has PBR textures.

  Vertices: 147 Faces:  144 Textures: Yes

Katana

Japanese sword with PBR textures.

Vertices: 558 Faces:  574 Textures: Yes

Short Shotgun

This model short shotgun comes in two parts, one the body of the gun and another the recharging system. The model has PBR textures.

  Vertices: 450 Faces: 404 Textures: Yes

RPG-7 – Rocket Launcher

This model of rocket launcher is separated, on one side the body of the weapon and on the other the projectile. It also has PBR textures made by me.

  Vertices: 775 Faces: 694 Textures: Yes

Introduction

In this article there are 3D models of tables to download and use in your projects at Unity.

For each model there are representative images rendered in Blender 2.8 and a brief description of the model, indicating topology data and materials.

The models are in .fbx format and can be imported directly into the Unity engine.

You can use these models to build prototypes quickly. I hope you find them useful.

Rectangular Table

This is a rectangular table for six people, has two materials, one for the legs and body parts and the second material for the top.

Vertices: 204 – Faces: 206 – Materials: 2

Oval Table

Table with oval top for six people, the legs are designed to be metal and the top of glass.

Vertices: 792 – Faces: 724 – Materials: 2


Small table

Small table for living room, designed with a metal structure and two pieces of glass.

Vertices: 168 – Faces: 156 – Materials: 2

Nightstand

Nightstand for bedroom, has a decorative drawer (does not open).

Vertices: 120 – Faces: 122 – Materials: 2

Corner table

Corner with two pieces of glass.

Vertices: 78 – Faces: 53 – Materials: 2

Introduction

In this article we are going to see the RigidBody component in Unity, what it is for and how to use it. Knowing about this component will allow you to create precise physics in your game.

What is a RigidBody in Unity?

First RigidBody in Unity is a “Programming Class” defined at the core of the engine and accessible via Script using the namespace “UnityEngine”. This in simple terms means that it is a programming structure that seeks to model a particular type of behavior. Here you can see an introduction to classes in programming.

RigidBody means Rigid Body, which in the study of physics is a way of thinking about certain objects and being able to make calculations and predictions in different scenarios.

The RigidBody class models the concept of Rigid Body in physics and allows us to treat GameObjects as if they were physical objects that have their own mass, are affected by gravity, can collide with other objects, exert forces on other bodies, have a coefficient of friction depending on the surface they are on, have linear and angular velocity, inertia, angular momentum.

To these bodies we can apply forces or torques and these Rigid Bodies will respond based on the classical equations of Newtonian physics. Beautiful!

What is a GameObject in Unity

Rigidbody Component in Unity

In the Unity hierarchy we have the list of GameObjects that are in the scene. If we choose one of them, we will be able to see its components in the inspector and add the ones we need to model its behavior. Here we can add to the GameObject the RigidBody component that will provide the physical Rigid Body behavior.

Colliders and RigidBody

Colliders are fundamental to being able to use a GameObject as a Rigid Body, as they provide the GameObject with a border to determine when it collides with other objects.

In the following video you can see different types of Colliders and in the final part how it relates to the RigidBody component. English Subtitles available.




Apply forces to a RigidBody in Unity

Because RigidBody is a class, it has a variety of public methods that allow you to access your internal state or perform certain functions. Among them is the possibility to apply a certain force to the GameObject. With the following instruction you can add a force to a Rigidbody:

aRigidbodyComponent.AddForce(forceVector);

Where “aRigidbodyComponent” is a variable which has the reference of a Rigidbody component and “forceVector” is a vector that describes the force to apply, that is to say its magnitude, sense and orientation.

Conclusion

RigidBody is a Programming Class defined in the engine core, accessible by the namespace UnityEngine. This class allows us to give GameObjects the behavior of physical Rigid Bodies with all that entails.

Colliders are essential to delimit the Rigid Body border and to calculate forces and collisions with other GameObjects with RigidBody.

Using the public methods of the RigidBody Class we will be able to apply forces, linear and angular velocities, torque and modify a great variety of properties present in the study of Newtonian physics.

Introduction

In this article we are going to analyze Unity’s FixedUpdate method which allows us to make changes over time in our projects.

A method is a function defined in a script that can be executed and performs the task we define inside it. To learn more about methods in programming you can read this article or watch a video that summarizes the information.

IMPORTANT

Here you have two videos about the FixedUpdate function in Unity. In the video on the left we see a prototype made in Unity to point the differences between the Update and FixedUpdate functions in Unity. You can download the Unity Package in this article. In the video from the right we see how to gradually change variables in Unity, making incremental changes inside the UPDATE or the FIXEDUPDATE method in Unity.

MY UNITY PLAYLIST WITH SEVERAL VIDEOS THAT YOU MAY FIND USEFUL
👇🏽

FixedUpdate Method in Unity – MonoBehaviours

The Update function is defined in the MonoBehaviour class and will run automatically in each frame of the game if the MonoBehaviour is active.

By default, the time between consecutive FixedUpdate runs is 20 milliseconds or 0.02 seconds. This time can be seen and modified in the tab Edit > Project Settings > Time – Fixed Timestep.

When we create a new Script in Unity, by default we’ll get some code already written. In this code is defined a Programming Class that is called equal to the name that we gave to the Script and that extends or inherits its behavior of MonoBehaviour, this in simple terms means that our Script is in itself a MonoBehaviour or a particular case of MonoBehaviour.

MonoBehaviours can be added to the GameObjects that are in the hierarchy, this can be done from the inspector using the “Add Component” button or simply dragging the Script to the GameObject inspector.

Execution of the FixedUpdate Function

While the game is running, Unity automatically takes all the MonoBehaviours on the scene and performs the FixedUpdate methods every time the “Fixed Timestep” time is met. So we don’t have to execute this method manually, the engine takes care of it.

This means that the FixedUpdate function will run periodically while our game is running.

Regardless of the FPS (frames per second) of our game, the FixedUpdate method will run at regular intervals, 50 times per second if the Fixed Timestep is set to 0.02 seconds.

Conclusion – FixedUpdate for evenly spaced changes in time

The FixedUpdate method represents the dynamic part of a game in Unity, when we want to produce changes in time and that these changes are applied at regular intervals, we resort to the FixedUpdate function.

A typical application of this function is to make the movement of objects or some animations that we do in a procedural way.

When moving objects in FixedUpdate, the speed of the object will be the one we indicate. If we move objects in the Update function, when our game runs at more FPS, the object will move faster than when the game runs slower.

It is useful to understand the order of execution of the Start, Update and FixedUpdate methods since it allows us to identify different moments in the execution of the game.

Introduction

In this article we analyze the Update function from the Unity engine, that function is defined inside the MonoBehaviour objects and it’s automatically executed every frame by Unity on every MonoBehaviour that is enabled.

So the update method allows us to make changes over time in our game or application made in Unity. For example we can move objects or gradually change a color inside an Update.

ABOUT THESE VIDEOS

Here you have two videos about the UPDATE FUNCTION in Unity. In the video on the left we see a prototype made in Unity to point the differences between the Update and FixedUpdate functions in Unity.


Update Method in Unity – MonoBehaviours

The Update function is defined in the MonoBehaviour class and will run automatically in each frame of the game if the MonoBehaviour is active.

When we create a new Script in Unity, by default we’ll get some code already written. In this code is defined a Programming Class that is called equal to the name that we gave to the Script and that extends or inherits its behavior of MonoBehaviour, this in simple terms means that our Script is in itself a MonoBehaviour or a particular case of MonoBehaviour.

MonoBehaviours can be added to the GameObjects that are in the hierarchy, this can be done from the inspector using the “Add Component” button or simply dragging the Script to the GameObject inspector.

Execution of the Update function

When running the game, Unity will automatically take all the MonoBehaviours in the scene and perform the Update methods before displaying each frame in the game. So we don’t have to do the execution of this method manually, the engine takes care of it.

This means that the Update function will run periodically while our game is running.

If our game runs at 60 FPS (frames per second) the Update function will run 60 times per second.

Conclusion – Update for changes in time

The Update method represents everything that is dynamic in our game, when we want to produce changes in time Update is one of the functions that we have to consider.

It is useful to understand the order of execution of the Start, Update and FixedUpdate methods since it allows us to identify different moments in the execution of the game.

Introduction

GameObjects are entities that we can place in Unity scenes, each GameObject will occupy a place in the hierarchy.

In the context of programming a GameObject is a Programming Class.



Basic features of a GameObject

Let’s see what are the basic features and components of an Empty GameObject which is the most general that we can add in a Unity scene.

Let’s consider that we have an Empty GameObject in the scene called “Object1”, with this GameObject we are going to exemplify the way to access its components.

Transform Component

GameObjects will have at least one Transform component that will indicate their position, rotation and scale in the scene.

We can access the reference of your Transform component using the dot operator as follows:

object1.transform

If we wanted to access the Vector3 that represents the position of the GameObject in the scene again we use the operator dot in the following way:

object1.transform.position

If we wanted to access the float that represents the component and the position of the object in the scene we can do the following:

object1.transform.position.y

The same applies for the other members of the Transform component.

object1.transform.rotation

object1.transform.scale

Tags

A GameObject has a Tag assigned to it that allows you to distinguish it from other GameObjects in the scene, list it using that Tag, or perform some function if the object has a certain Tag assigned to it.

Layers

Layers are assigned to GameObjects and in the same way that Tags allow us to list them and perform actions if the GameObject belongs to a certain layer.

A more interesting application of Layers is in the rendering of GameObjects. We can configure several cameras in the scene and make each camera capture one or more particular Layers.

SetActive Method

This method allows you to enable or disable the GameObject in the hierarchy through code, the result is equivalent to marking or unchecking the tilde at the top of the inspector when the object is selected.

To activate it we do:

object1.SetActive(true);

To deactivate it:

object1.SetActive(false);

A video on how to activate and deactivate GameObjects through code




GetComponent Method

This method allows to obtain the reference of a component of some specific type that is assigned to the GameObject. To find out what a method is in programming you can click here.

Suppose our GameObject is called “object1” and has an AudioSource type component assigned to it, this AudioSource component will allow the GameObject to emit sounds. Now, if we want to access through code to the AudioSource component attached to our GameObject, for example to gradually lower down the volume, we can do it with the GetComponent function, this way:

object1.GetComponent<AudioSource>();

The previous intruction returns us the AudioSource reference assigned to the “object1” GameObject.

If the GameObject has more than one such component, we can do the following:

object1.GetComponents<AudioSource>();

This returns an Array containing all the components of that type that the object has assigned to it.

Flexibility to build complex GameObjects

We mentioned that Empty GameObject is the simplest type of object we can find in a scene in Unity.

We can customize these objects as much as we need, add pre-existing components in the Unity engine or our own programming scripts. This will make each GameObject have a specialized behavior.

Conclusion

We have seen what a GameObject is in Unity, what are its main components and the possibility of adding as many components as necessary to build the objects we need in our world.

The simplest object in a scene will be assigned a Transform component that will indicate its position, rotation and scale in the scene. It will be assigned a Tag and a Layer that allow grouping objects and performing appropriate functions for each group.

In the field of programming GameObject is a class of programming, which has fields and methods that define it. You can consult the list of all its members in the API of Unity.

Exit mobile version
Secured By miniOrange