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!
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.
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.
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 👇🏽
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.
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.
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
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 this article we are going to study the geometric figure circle, its characteristics and mathematical equation.
Definition of a circle
A circle is a geometric figure in which all its points are at the same distance from a given point called the center, this distance is known as the radius of the circle.
Fig. 1: Graph of a generic circumference of radius R and centre at point (a,b).
Equation of a Circle
Knowing the mathematical expression of a circumference we will be able to draw it in the Cartesian plane and later use it in our projects of programming and development of videogames.
Cartesian coordinates
The expression that defines a circle in Cartesian coordinates is the following:
(1)
Where R is the radius of the circumference and its center is located at point (a,b) of the Cartesian plane.
In this case to draw the circle we must know the range of values of the variables X and Y. For example, let’s consider the circle unit centered in (0,0):
(2)
If we draw a circle of radius 1 with center in (0,0) we can see that both the values of X and Y will be in the interval [-1,1]. By choosing a value from that interval and assigning it to one of the variables we will be able to clear the equation and obtain the value of the other variable.
Parametric coordinates
The expression of a circumference in the parametric coordinate system may also be useful, since the range of variation of the parameter is infinite since it is defined with periodic functions. The expression of a circle is given by the following system of equations.
x=a+r.cos(t)
y=b+r.sin(t)
(3)
By varying the t parameter between 0 and 2π we obtain all the points of the circumference.
As we mentioned before the parameter t can take values from less infinite to more infinite and will always return some point of the circumference, because the sinuses and cosines are periodic functions.
Circle and mathematical functions
It must be borne in mind that there is no mathematical function that defines the circle since, by definition, a function is an expression in which it is fulfilled that, for each value of the independent variable, there is only one value for the dependent variable.
In others for it to be a function we must be able to draw a vertical line anywhere on the graph and this should cut the function into a single point. This does not happen in the circle, since if we take for example the line coincident with the Y axis, we see that it cuts the circle unit centered in (0,0) in two points.
What we can do is clear the variable and in equation 1.
(4)
The absolute value arises when taking the square root of an expression that is elevated to the square, this gives rise to two possible values for that expression, one positive and the other negative, that define the lower and upper cap of the circumference.
Semicircle – Concave from below
The expression of the function that represents the top semicircle of a generic circle is:
(5)
Semicircle – Concave from above
The expression of the function that represents the bottom semicircle of a generic circle is:
(6)
Perimeter of a circle
The perimeter of a circle is the length of its boundary, let’s imagine that we make a mark in a point of the circle, we place that point in the 0 of a line and we make it turn forward, the point where the mark touches the line again is the value of the perimeter of the circumference. Mathematically it can be calculated as:
(7)
Pi has an approximate value of 3.1415 and r is the radius of the circumference.
Area of a circle
The area of a circle is the result of multiplying the number Pi by the radius of the circle squared. Mathematically:
(8)
Introduction
In this article we are going to see how to export 3D models, with materials, UV maps and animations, from Blender to the Unity engine, in which format and a some useful tips to prepare models before exporting.
The process is simple, being in object mode, we select the 3D model or models that we want to export. Then click on File > Export and choose the format to which you want to export it.
In my case I always check the “Selected Only” box to export only the selected 3D models to Unity.
Format to use
The format I use is .fbx (Filmbox), which has not given me any inconvenience and allows me to export the materials contained in the 3D model, the animation skeletons, the actions defined with the Action Editor and the Shape Keys.
Things I take into account before exporting
Before exporting from Blender to Unity I try to improve certain aspects of the 3D model in order to have everything as organized and simple as possible.
About the names of the 3D models
In Blender’s Outliner we can modify the names of objects and since those names are going to be exported directly from Blender to Unity, I like them to be as descriptive as possible.
In the long run, when we have many 3D models in our project, organization is fundamental.
About the origins of 3D models
The origin of an object is the point in the space that represents it. The transformations of translation, rotation and scale of the object will be applied with respect to that point. So, in general, we are interested in its being in a coherent place in the 3D model.
We enter the geometry editing mode and select a vertex, edge or face where we want to place the origin. Then press “CTRL + SHIFT + S” and choose the option “Cursor to Selected”, to move the 3D cursor to the selected element.
Go back to Object mode, right click on the 3D model, go to the “Set Origin” option and choose “Origin to 3D Cursor”. This will place the coordinate origin of the 3D model in the position where the cursor is.
Introduction
In this article we are going to see what is a floating point and how decimal values are represented using this system.
Floating point representation is a way of writing a decimal number that resembles scientific notation. This allows us to represent and operate with very large numbers and also with very small numbers (with many decimals).
The floating point computing standard is described in IEEE 754.
Structure of a floating point number
This representation system uses a certain number of binary digits depending on the type of accuracy (commonly 16, 32, 64 and 128 bits).
A bit is destined to the sign, i.e. if that bit is worth 0 it is a positive number, if it is worth 1 it is a negative number.
The remaining bits are distributed in the representation of the decimals (usually called mantissa) and the exponent.
In the expression n it is the decimal number to represent.
The letter s is the bit for the sign (if s is 0, the expression (-1) raised to 0 results in 1 positive).
The letter e is the exponent and m is the mantissa.
Move decimal numbers to floating point
1- Take the number to represent, separate the sign and write the absolute value in base 2.
2- The absolute value in base 2 is written in scientific notation in normalized base 2.
3- The exponent is expressed in excess notation (it will depend on the type of precision chosen).
4- The coefficient is written on the mantissa without the whole part, because the normalization in step 2 forces the whole part of the mantissa to be 1, storing it does not provide information.
System Truncation Error Floating Point
A truncation error occurs when you take a certain number of digits from one number and leave out the others.
Think of the number π (3.14159265…), which is an irrational number with infinite digits.
Computers cannot store infinite information in memory because infinitely large memory would be needed, so at some point it must stop.
If we truncate all the decimal part to π and we are left with only 3, we will be making an error of approximately 4.5% relative to the real value of π . If on the other hand we take into account the first two decimals of π, we are left with 3.14. In this case we will be making an error of approximately 0.05% relative to the real value of π.
This error will occur in the floating point system either because we want to represent irrational numbers or because the decimal we want to represent becomes irrational when passed to the binary system (example 0.1 decimal has infinite digits when passed to binary).
Introduction
In this article we will look at what a programming paradigm is for information purposes and give some examples.
The first generations of computers were programmed using machine language, i.e. a sequence of instructions was given that the machine understood. As it was difficult to remember the codes of these instructions, the Assembler language was created, which also consisted of a set of instructions for the machine, but written with words simple to remember.
With advances in technology, programming languages emerged, allowing programmers to increase the level of abstraction and solve more complex problems.
What is a Programming Paradigm?
Programming in high-level languages can take several forms, i.e. we can tackle problem solving from different angles.
There are different ways of designing a language and various ways of working to get the results that programmers need. These ways of thinking or working are called PROGRAMMING LANGUAGE PARADIGM.
A continuación vamos a mencionar algunos de estos paradigmas.
Imperative Paradigm
Programs consist of a succession of instructions or commands, as if the programmer were giving specific commands.
This is the simplest way to attack problems, but it becomes inefficient when problems are complex.
Logical Paradigm
This paradigm, as its name indicates, is based on logical thinking, which is natural for us to understand. Using logic, complex problems can be expressed in a formal way, elaborating premises and then applying hypotheses, axioms and theorems for resolution.
Logical programming is optimal in artificial intelligence applications. The Prolog language uses this paradigm.
Functional Paradigm
This paradigm consists of creating functions that solve a certain type of problems and then calling them when needed. These functions may contain other functions within them.
Some languages that use this paradigm are Haskell and Python.
Object Oriented Paradigm
In this paradigm models of objects are constructed, which are abstract entities that have defined a set of data and functions inside.
Some languages that use this paradigm are C++, Java and C#.
Introduction
In this article I show some of the Blender timelapses I have made in the last time.
Timelapse is a technique used to show a slow process in an accelerated way. I like to see 3D modeling timelapses because they are entertaining and new ways of doing things are usually discovered.
Rubik’s Cube
This was the first one I made for the channel, a Rubik’s cube that you get by first modeling a cube with rounded edges and then duplicating until you have all the pieces.
Materials are defined from the Shader Editor (in Blender 2.79 was the Node Editor), no textures are used.
Chess Pawns
A pair of chess pawns made in two different ways in Blender, in one we start from a sphere and the faces are extruded downwards and in the other one we start from a circle for the base and extrusions are made upwards.
To help shape the parts is modeled with a reference image located in the background, this is especially useful for revolving parts.
Venetian Mask
Another example of 3D modeling with reference image, in this case the reference is used to copy the topology of a 3D face in a precise way, this will make it respond better to proportional deformations and subdivisions.
I think it’s a good way to study how to model faces in 3D.
Torii – Japanese Gate
I really liked making this timelapse, although I had to do it twice because in the first time I adjusted the program badly to capture the screen.
In this case I researched a little to find royalty free music that fits the model and found a channel called PeriTune that had very nice melodies and some could be used in the videos. They also have a website.
Kokeshi – Japanese Doll
This is one of the first 3D models I made using Blender 2.8 and its new Eevee rendering engine.
I found Eevee’s ability to apply effects in real time great, but at first I found it hard to get used to new things, such as selecting with the left click.
I had to do the timelapse twice because the first time I had a problem with the catch.
Skyrim’s Lockpick System
I’m doing a lockpick analysis of Skyrim for my page. My intention is to recreate it in Unity as faithfully as possible and the first step is to create the 3D model.
In this timelapse not only do the modeling and UV maps in Blender but I use Substance Painter to create the textures, is a great software that I acquired a few months ago.
Introduction
In this article we are going to see what a quadratic function is, its mathematical expression, its characteristics, how to graph it in the Cartesian plane and what it can be useful for in the development of games with examples in Unity.
Mathematical expression of a quadratic function
The polynomial expression of a quadratic function is:
It is commonly read “f of x”, being X the independent variable, a, b and c constant real numbers.
Characteristics of a quadratic function
Domain
The domain is the range of allowable values for the independent variable, commonly referred to as X.
In the case of the quadratic function the domain is the set of real numbers.
In other words we can choose any value of X belonging to the set of real numbers and we will find its corresponding value f (X).
The roots of a quadratic function are the values of x for which f (x) is worth 0, i.e. the points at which the function touches the abscissa axis (commonly the x-axis).
There can be three cases, the function has a root, i.e. there is only one value of x for which the function is worth 0.
The function can have two roots, i.e. there are two different values of x for which the function is worth 0.
The function may not have roots in the set of real numbers but in the set of complex numbers.
To calculate the roots of a quadratic function we use a formula commonly known as the Bhaskara formula.
Given the following equation:
The two values of x that satisfy this equation are given by:
The plus-minus sign ( ± ) means that they are two equations, in one we use the plus sign and get X1 and in another we use the minus sign and get X2.
As an observation, if what is inside the square root gives as a result a negative number it means that the equation has no solution in the set of real ones, in this case we see graphically that the parabola does not cut the axis of the abscissas.
Some examples in Unity of quadratic function
Draw parabolic trajectories
We might be interested in drawing parabolic trajectories through code, for example for particle systems, or to represent the possible trajectory a projectile can follow when launching it.
In the following video I show how a set of GameObjects follow a parabolic path described by two quadratic functions to which the parameters can be adjusted.
Observation 1: spheres of the same color follow the path defined by the same equation only that for one I take the constant a as positive and in the other as negative, for this reason they are reflected with respect to the axes.
Note 2: Notice that at the beginning and end of the video the value of a is 0, this means that the quadratic term is annulled and we are left with a linear function.
In physics there are many quadratic magnitudes that we might be interested in implementing in our game.
An example of this can be motion with constant acceleration, i.e. objects that move with velocity that changes linearly. For example, bodies in free fall by the action of gravity or vehicles that accelerate.
Some types of energy such as kinetic energy or elastic potential energy are proportional to the square of a magnitude.
Conclusion
The quadratic function is a polynomial function of order 2 whose graph in the Cartesian plane is a parabola.
The roots of the quadratic function are the values of x in which f (x) = 0 is fulfilled. We can use Bhaskara’s formula to find them.
A quadratic function can have two different roots, a root or not have roots in the set of real numbers. If a quadratic function does not have real roots, it does not graphically intersect the abscissa axis.
There are physical magnitudes as well as trajectories of accelerated bodies that can be described by quadratic functions, so it is useful to have knowledge about their characteristics and thus be able to implement them correctly in Unity.
Introduction
This article will function as the practical part of the previous article on Classes in Programming. We are going to solve an exercise on class structure and implement it in C# in Unity.
If you don’t know what a class is in programming it would be good if you saw the article I wrote on the subject before continuing.
Let’s see an example that occurred to me at the time of writing this article. It’s about modeling the behavior of a village that has inhabitants and these inhabitants can be workers or warriors.
I have highlighted what I consider to be key words in raising the problem, in principle it seems that at least we are going to need two classes to solve it, one for the village and one for the villagers, but we are going to consider the fact that both workers and warriors themselves are villagers.
Workers and Warriors will have common characteristics and behaviors that will be defined in the Inhabitant class and then the Worker and Warrior classes will inherit the characteristics and behaviors of Inhabitant.
A village has inhabitants so the Village class will have among its data one or more instances of the Villagers class.
I would like to mention that knowing the difference between classes and instance of classes is very important, but this article is not about that, just as it is not about inheritance.
At the moment the idea is that we are going to use the Inhabitant class to create all the inhabitant objects that we need, these objects will have their own values (for example different names or age) but they will respect the structure defined in the class.
Class Diagram
Then we said that we are going to use four classes, Village, Villager, Worker and Warrior. The Village class has among its data one or more instances of the Inhabitant class. Worker and Guerrero are a specific type of Inhabitant so inheritance will be used.
The class diagram in Figure 1 is based on the previous paragraph.
Fig. 1: Example of what a class diagram might look like in a project
In the diagram we observe a “1..*” above Inhabitant, this means that Village will have one or more Inhabitant objects.
In addition, we observe that the inheritance of classes is represented by an upward arrow toward the parent class.
Object Diagram
Once the classes that will be present have been defined, we think about their possible fields and methods. In this part it is good to reflect on the nature of the object we want to model, what its characteristics are, what information it handles and what its behaviour may be.
I’m going to make up some fields and methods for the classes because this practice of programming classes is more about the approach of class structure and its later implementation in Unity in C# language, but without going into details of what is going to be done with this.
Figure 2 shows the object diagrams of the four classes.
Fig. 2: Using these boxes we indicate the attributes and methods, public and private, of the classes.
Now I am going to explain in detail how the boxes in figure 2 are interpreted.
The Village Object
For this object I considered that every village has a name and a group of inhabitants, so for its fields I am going to use a collection of objects called “inhabitants”, a string called “name” and an integer called “population”. I place these fields at the top of the box as shown in figure 2.1.
Some methods of the object Village can be “NewInhabitant” which will be executed every time an inhabitant is born. “GetName” and “GetPopulation” will return the corresponding data (they are known as “Getters” and are useful for example to make statistics of all the villages we may have).
The “InhabitantDie” method can modify the population and remove the dead inhabitant from the collection of inhabitants.
Fig. 2.1: Object diagram for the Village class, where we see the fields and methods of the class.
Finally, the “Feed Inhabitants” method, which can go through the collection of inhabitants executing appropriate methods in each of them, or check the food reserve and subtract as many units as there are populations.
El objeto Habitante
Inhabitant will be the parent class (or superclass) of Worker and Warrior, in this class will be defined the behavior and data that have in common Workers and Warriors.
Every inhabitant has a name represented by a String, an integer for age, another for health and another for defense.
Fig. 2.2: Object diagram for the Inhabitant class, where we see the fields and methods of the class.
Among the methods of Inhabitant we have the “Getters” to obtain name and age, a private method to age and a public method for the inhabitant to move to a position.
The Worker Object
The Worker Object is a more specific case of the Inhabitant class, between its fields we have a string that indicates the name of the work and a boolean variable to know if it is working or not.
Worker methods are related to what your activities could be, for example Collect, Repair, Drill, Fish and also a private method for you to deliver the resources it has obtained. This last method can be executed internally by Worker for example when it is at the limit of its collection capacity.
Fig. 2.3: Object diagram for the Village class, where we see the fields and methods of the class.
The Warrior Object
The Warrior class is a more specific case of the Inhabiting class.
A Warrior may or may not be attacking for which we use the Boolean variable “attacked”, has assigned a weapon represented by a String and has certain attack points represented by an entire variable.
Among its methods are Attacking, Formation, Defending, and a private method to deliver the booty he got after a successful battle.
Fig. 2.4: Object diagram for the Warrior class, where we see the fields and methods of the class.
Implementation in Unity
Now we move on to the good part, let’s take the class diagram and the object diagram from figures 1 and 2 and use them as a reference for creating classes in Unity.
Before you start you might need to know how to use Unity, here on the page I have a couple of series, one called “Unity Fundamental Series” and the other “Labyrinth Game“, the first one has specific themes and the second one is a mini project. You can find all the articles using the navigation menu and there are also the videos in the channel.
Let’s go on, in a Unity project we created the four classes from the diagram in Figure 1.
Fig. 3: Create the necessary C# scripts according to the class diagram in figure 8.
By convention, class names begin with a capital letter and CamelCase is used if the class name has more than one word. For example the class “Long Range Weapon” could be written “Long RangeWeapon”, better still if we get used to using the English name “LongRangeWeapon”.
A clarification, as seen in the article: “What is a Class in Programming“, when creating a new class in Unity, it will inherit from MonoBehaviour, which will allow Unity to consider it in its internal cycle. Let’s leave this inheritance as it is, even if we haven’t made it explicit in the class diagram in Figure 1.
If we wanted to make a more accurate diagram we should place the MonoBehaviour class and make both Village and Inhabitant inherit from it.
As a clarification it is good to say that our classes are going to be MonoBehaviours, however it does not make sense to pose an extremely complete class diagram since MonoBehaviour inherits the Behaviour class, which in turn inherits the Component class, who finally inherits the Object class. It is not necessary to go that far, we must focus on what is important to solve our problem.
The Village class
To write the corresponding code in the Village class we must look at the Village Object diagram and simply know the syntax of the object-oriented language we are going to use, in this case C#.
In figure 4 we see how the diagram in figure 3.1 is implemented using the C# language in Unity.
Notice how the names, data types, and visibility indicated in the object diagram are respected.
Fig. 3.1: Object diagram for the Village class, where we see the fields and methods of the class.
Fig. 4: We define the necessary attributes and methods, taking into account the boxes in figure 9.
This is the idea of practicing Classes in programming, creating classes in Unity based on an analysis of the problem and diagrams of classes and objects.
We are not going to write anything in the methods because it is something that depends on the purpose of the solution we are proposing.
The Inhabitant Class
Fig. 2.1: Object diagram for the Inhabitant class, where we see the fields and methods of the class.
Fig. 5: We define the necessary attributes and methods, taking into account the boxes in figure 9.
The Worker Class
Fig. 2.1: Object diagram for the Village class, where we see the fields and methods of the class.
Fig. 6: We define the necessary attributes and methods, taking into account the boxes in figure 9.
The Warrior Class
Fig. 2.1: Object diagram for the Warrior class, where we see the fields and methods of the class.
Fig. 7: We define the necessary attributes and methods, taking into account the boxes in figure 9.
Conclusion
In this practice of Classes in Programming, we have seen how, from the point of view of a problem, we propose a structure of classes to model the behaviour of the elements.
We represent the structure of classes using a Class Diagram in which we show what is the relationship that exists between them.
The Classes will have their members, i.e. Fields and Methods, we can represent them using Object Diagrams, in which we show names and types of data for the Fields and the methods that the class will have. Also the visibility of each one.
All of the above is independent of the programming language, it is about intuitively modeling an object-oriented solution.
To implement it in Unity in language C# we will have to know the own syntax of the language, nevertheless it is extremely interesting to know that this same one could be reused for example for an Android application using language Java in Android Studio.
Introduction
In this article we are going to see what is a CLASS in programming, what are its components, class diagrams and of course we are going to see examples in C# using Unity.
If you already know about this topic I invite you to see the practical part of this article in which I pose a problem to create a class structure, make diagrams and then program the solution in Unity.
The concept of Class is linked to object-oriented programming.
When we program in C# using Unity, when we create a new Script we automatically create a class that is called the same as the Script.
The terminology we use when referring to a class probably changes depending on the bibliography or the teachers, but if we can grasp the basic idea we can use this knowledge to create solutions for our projects.
What is a class in programming?
A class is a tool we have to model programming objects, make them behave as we want and make as many copies of them as we need.
For now let’s just think of it as code that is encapsulated in a programming script.
How to define a programming CLASS
Depending on what we are doing, creating a class will be done one way or another. In general what we will do is create an instruction file with the extension of the programming language we are using and whose name will coincide with the name we give to the class in its declaration.
In general, development environments simplify the process of creating a class. For example in Unity from the project folder we can right-click and use the menus to create a new C# Script, as shown in figure 1.
Fig. 1: From the project window you can create new C# Script.
To show some examples of classes in Unity, I am going to create the three Scripts that are observed in figure 2.
Fig. 2: I am going to create three Scripts to exemplify the classes in programming.
Example 1, default class
When we create a new script, when we open it we are going to find some code already written.
In figure 3 we can see that in the first three lines are imported some libraries that will allow us to access the functionality of the Unity engine.
Then it is observed that a class called “Class1” is defined, the definition of the class begins in line 5 and ends in line 18 with the closing of the key.
Something we also see is the “MonoBehaviour” to the right of the class name, this means that our “Class1” is going to be an extension of the MonoBehaviour class, which is known as inheritance.
Inheritance is a great topic and we are not going to delve into this article, for the moment think that if a class called Class 1 inherits the class MonoBehaviour, means that Class 1 is itself a MonoBehaviour but with more specific functionality.
It’s like thinking about dogs and cats, these are different species but share certain characteristics such as the number of legs and also have similar behaviors such as walking, running, eating and breathing. This means that we can group them for example in a class called SerVivo, Animal or Quadruped (no accents are used in programming).
MonoBehaviour is like the basic class of GameObjects in Unity and allows these to be automatically initialized through the Start method and also automatically runs the Update methods (also defined automatically when creating a class, lines 8 and 14 of figure 3) and FixedUpdate for example. For more details about the MonoBehaviour class you can take a look at the Unity API.
Fig. 3: The first example shows what a new script looks like. This is the Class1 class that inherits the MonoBehaviour class.
Example 2, Object subclass
In the example in figure 4 the inheritance of MonoBehaviour has been removed, this implies that Class2 will inherit implicitly from the “Object” class, which is probably the mother of all the classes we are going to use in Unity.
By removing the MonoBehaviour the green comments in lines 7 and 13 of figure 4 are no longer true. These Start and Update methods will not be executed automatically.
It is not normally used in Unity this type of classes that derive directly from Object.
Fig. 4: In the second example we eliminate the inheritance of MonoBehaviour, which means that Class2 inherits Object.
Example 3, subclass of another class
This example is similar to example 1, we can make classes that derive from other classes (inheritance of classes), not necessarily MonoBehaviour but any UnityEngine class or that we have created.
In figure 5 we see that Class 3 inherits Class 2.
Fig. 5: La clase Clase3 hereda de la clase Clase2.
Example 4, Java classes
Usando NetBeans IDE hice un par de clases en Java para mostrar, aunque Unity no usa Java, es interesante ver las similitudes y diferencias.
Las siguientes clases serán análogas a las creadas en los ejemplos 2 y 3.
La Figura 6 muestra una clase llamada Clase1 derivada de Objeto mientras que la Figura 7 muestra una clase llamada Clase2 derivada de Clase1.
Fig. 6: Definition of class in Java using NetBeans IDE.
Fig. 7: To indicate that inheritance is used the word extends.
Components or members of a class
The classes in programming are used to model objects that we want to fulfill a function.
Fields
It is the data that the class has, they can be variables or even instances of other classes.
For example, a class called “Auto” might have a boolean variable to indicate whether it is on or off. A float variable to indicate the speed and another for the remaining fuel.
We could use a three-dimensional vector (“Vector3” class in Unity) to determine the speed and direction of motion.
Also the class “Auto” could have between its fields the instance of another class called “Motor”, which in turn will have its own members defined.
Methods
Methods are those that provide functionality to a class, allowing it to perform tasks, manipulate its fields and interact with other classes.
Returning to the example of the “Auto” class that has among its fields the “Motor” class.
Suppose Auto has a method called “Accelerate” that progressively increases the speed of the vehicle.
Class Diagram
A useful tool when it comes to reflecting the structure of classes that we will make to propose a solution is the class diagram, in which we will show the different classes, the relationship that exists between them and we will show the inheritance of classes that may exist.
In figure 8 we see an example of a class diagram based on the practical exercise of classes in programming.
Fig. 8: Example of what a class diagram might look like in a project
Objects Diagram
Once we have defined the classes that will be present we think about their possible fields and methods, in this part it is good to reflect on the nature of the object we want to model, what are its characteristics, what information it handles and what can be its behavior.
We can represent the fields and methods of a class using “Object diagrams” that in general are drawn with a box for each class, indicating fields and methods using the names that we are going to give them in the script and separated by a line (in my case to the methods I add the symbols “( )” to indicate that they are methods). For the fields we also indicate the type of data.
Another thing we can indicate is the visibility of fields and methods, using a “+” sign for fields and public methods and the “-” sign for fields and private methods.
Figure 9 shows Object diagrams for the 4 classes of the class diagram in Figure 8.
Fig. 9: Using these boxes we indicate the attributes and methods, public and private, of the classes.
Conclusion
In this article we have seen what a class is in programming, it is like a template that will allow us to create instances of objects that will have the attributes and methods that we have defined in the class.
Classes have defined within them fields and methods that together will define their nature and behavior.
The class diagram helps us to represent the relationship that exists between our classes.
The object diagram allows you to represent the fields and methods of a class along with their visibility.
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are as essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.