#6 Programming the User Interface in Unity

Updated information about this project

This arti­cle belongs to a series that con­sist on mak­ing a first per­son game about find­ing objects inside a maze. It's one of my very first series from the chan­nel. Now I reworked this project and you can down­load it to import in your own Uni­ty project. Some day I will make a new series about this project, sub­scribe to my chan­nel to see all the fresh con­tent about Blender, Uni­ty and pro­gram­ming.

Follow me on itch.io and download the source code of this project

YOU CAN TRY THIS GAME HERE, IT MAY TAKE A LITTLE WHILE TO LOAD
🔻

MOVEMENT: WASD CAMERA LOOK: MOUSE

Introduction of the old article

In this arti­cle we will pro­gram the log­ic of the user inter­face cre­at­ed in video 5 of the labyrinth series. If you did not read the pre­vi­ous arti­cle, in sum­ma­ry we cre­at­ed a user inter­face in Uni­ty, which will have the min­i­mum func­tion­al­i­ty for the user to inter­act with the game.

Go to the project's Main Page

Video related to this article

Before we begin I invite you to watch this video. 


Objective of this article

In the pre­vi­ous arti­cle we designed a sim­ple user inter­face so that the user can con­trol the fun­da­men­tal aspects of our game, such as start­ing the game, know­ing how much time he has left, etc…

At this point we are going to use the Game­Con­trol Script to man­age the user inter­face. In the fol­low­ing chap­ters we will del­e­gate this respon­si­bil­i­ty to a new Script.

To sum­ma­rize the ele­ments of the user inter­face we have two screens, one for the main menu which con­tains only one but­ton that serves to start the game. The sec­ond screen is for the game and has a text ele­ment that will show the amount of time left to fin­ish the game.

Resolution

In the Game­Con­trol Script we define three seri­al­ized GameOb­jects, one for the cam­era that is active in the main menu, anoth­er for the menu inter­face and anoth­er for the game interface.

The three GameOb­jects defined are high­light­ed in Fig­ure 1.

script c# para unity 3d con tres gameobjects seleccionados
Fig. 1: Three seri­al­ized GameOb­jects are defined for the cam­era and inter­face displays.

In fig­ure 2 we can see that these new fields appear in the inspector.

inspector en unity 3d, en los espacios se colocarán gameobjects de la interfaz de usuario
Fig. 2: The three GameOb­jects appear in the inspector.

We take the objects cre­at­ed in the pre­vi­ous video and drag them to the fields in the inspec­tor. These objects are the cam­era, the GameOb­ject Main­Menu and the GameOb­ject Game.

jerarquía en unity 3d con game objects
Fig. 3: We take the GameOb­jects from the hier­ar­chy and take them to the inspector.

inspector en unity 3d, se han colocado todos los gameobjects de la interfaz de usuario
Fig. 4: In the inspec­tor we place each GameOb­ject in its cor­re­spond­ing space.

StartGame and EndGame methods

We are going to define two meth­ods, one is going to be called "startGame" and the oth­er "endGame". The startGame method will have the func­tion of doing every­thing nec­es­sary for the game to start, i.e. set­ting the timer to zero, plac­ing the character's pre­fab, plac­ing the pedestal in a ran­dom posi­tion on the stage and so on. Keep in mind that these actions will prob­a­bly be defined in oth­er methods.

In the endGame method we remove all objects from the sce­nario, go to the main menu and so on.

script c# para unity 3d metodos startGame y endGame para empezar y terminar juego respectivamente
Fig. 5: The startGame and endGame meth­ods are defined.

In the meth­ods we are going to acti­vate and deac­ti­vate the cor­re­spond­ing ele­ments, as can be seen in fig­ure 6.

script c# para unity 3d metodos startGame y endGame para empezar y terminar juego respectivamente
Fig. 6: Inside each method we place the appro­pri­ate instructions.

Let's go to the hier­ar­chy and select the "Start" but­ton, to observe its prop­er­ties in the inspector.

jerarquía en unity 3d con game objects, esta seleccionado el boton start de la interfaz de usuario
Fig. 7: The start but­ton in the hier­ar­chy is selected.

inspector en unity 3d con un botón de la interfaz de usuario seleccionado
Fig. 8: In the inspec­tor click on the plus sign to add a func­tion to OnClick().

In the But­ton com­po­nent there is a field called OnClick(), let's click on the plus sign in the low­er right cor­ner, in fig­ure 8 the cur­sor is over this button.

This will allow us to run pub­lic meth­ods with­in the GameOb­ject com­po­nents we assign.

In the field that appears we are going to place the GameOb­ject Control.

inspector del metodo OnClick de button en unity 3d
Fig. 9: A space appears for plac­ing a GameObject.

asignacion de un gameobject en el metodo onclick en el inspector de unity 3d
Fig. 10: Place the Con­trol object assigned to the Game­Con­troller Script.

Aho­ra uti­lizan­do el menú desple­gable, podemos acced­er a las com­po­nentes y sus métodos.

selección de función para el método onclick en unity 3d
Fig. 11: With the drop-down menu you can select a method from one of the com­po­nents of the Con­trol object.

Como se tra­ta del botón Start, esta­mos bus­can­do el méto­do StartGame que hemos definido en el Script Game­Con­trol, en la figu­ra 12 podemos obser­var los atrib­u­tos y méto­dos públi­cos del Script Game­Con­trol y vemos que StartGame no se encuen­tra entre ellos.

selección de función para el método onclick en unity 3d
Fig. 12: The startGame method does not appear between the functions.

This is because we use pri­vate vis­i­bil­i­ty in the definition.

To solve the prob­lem, we changed the method to pub­lic vis­i­bil­i­ty, as shown in Fig­ure 14.

script c# para unity 3d metodos startGame y endGame para empezar y terminar juego respectivamente. control de la interfaz de usuario
Fig. 13: We had defined the startGame method as private.

script c# para unity 3d metodos startGame y endGame para empezar y terminar juego respectivamente. control de la interfaz de usuario
Fig. 14: We change the vis­i­bil­i­ty to public.

Aho­ra podemos ele­gir que se eje­cute este méto­do cuan­do se haga clic en el botón Start.

selección de función para el método onclick en unity 3d
Fig. 15: The startGame method now appears in the functions.

I arrange the cam­era a lit­tle so that the small scene of the doors is seen and I enter the game mode to test the oper­a­tion of the button.

escena en unity 3d vista superior, el suelo es de cesped
Fig. 16: Arrange the main menu camera.
prueba de la interfaz grafica en unity 3d
Fig. 17: Enter game mode to test the button.

Bug fixing

When enter­ing game mode, the char­ac­ter appears on one of the doors ran­dom­ly, but for some rea­son the con­trols don't work prop­er­ly, the char­ac­ter drags on the floor and the cam­era turns in a strange direction.

bug en unity 3d, el personaje aparece caido en el suelo
Fig. 18: The game starts but there seems to be a prob­lem with the character.

bug en unity 3d, el personaje aparece caido en el suelo
Fig. 19: The char­ac­ter appears on the side and can­not move.

The Debug­ging process can be a bit tor­tu­ous, luck­i­ly we have tools to ana­lyze the flow of the pro­gram, dis­cov­er the parts of the code that work prop­er­ly, see the val­ues of the vari­ables and so on to detect the prob­lem and be able to cor­rect it.

With­out going into details, because I hon­est­ly don't remem­ber how I dis­cov­ered the bug, the prob­lem had to do with the hier­ar­chy struc­ture between GameOb­jects and the inher­it­ed trans­for­ma­tion of the par­ent GameObject.

To cor­rect the prob­lem in the instruc­tion to instan­ti­ate the char­ac­ter, with­in the "pla­ce­Play­er­Ran­dom­ly" method, change the rota­tion from local to glob­al, as seen in fig­ures 20 and 21. 

script c# para unity 3d metodo placePlayerRandomly para colocar al jugador aleatoriamente en el escenario
Fig. 20: The pla­ce­Play­er­Ran­dom­ly method is the one that places the char­ac­ter on the stage.
script c# para unity 3d metodo placePlayerRandomly para colocar al jugador aleatoriamente en el escenario
Fig. 21: In the instan­ti­ate instruc­tion we change local­Ro­ta­tion for rotation.

This cor­rects the prob­lem and we can use the start but­ton to start the game.

modo juego en unity 3d, suelo de cesped con margaritas y una puerta antigua de madera
Fig. 22: The char­ac­ter now appears cor­rect­ly on the stage.

Final details

When you enter the game mode, the first-per­son con­troller pre­fab cap­tures the cur­sor, places it in the cen­ter of the screen, and hides it.

This is a prob­lem because when we return to the main menu when the game is over we can't click on the but­tons. So the solu­tion is to unlock the cur­sor and make it vis­i­ble at the end of the game, i.e. in the endGame() method.

To find out how to do this let's ana­lyze the MouseLook Script that uses the con­troller in the first per­son. In fig­ure 23 we can see this Script along with its route to get to it.

cuatro scripts de unity 3d en la ventana proyecto
Fig. 23: Abri­mos el Script MouseMi­ra den­tro de First­Per­son­Char­ac­ter de Stan­dard Assets.

Fatal Error

When try­ing to open MouseLook the edi­tor fails and must be closed los­ing all unsaved changes! It is impor­tant to save at all times, the CTRL+S access is very useful.

fallo en editor de scripts mono behaviour durante un proyecto en unity 3d
Fig. 24: When open­ing the script an error occurs and all unsaved changes are lost.

On the sec­ond attempt we were able to access the script. We are look­ing for an instruc­tion relat­ed to the Cursor. 

We see that in lines 93 and 94 of fig­ure 26 there are a cou­ple of instruc­tions that seem to be the indi­cat­ed ones so we copy them. 

script mouse look de firstpersoncharacter standard assets
Fig. 25: Check the MouseLook script for instruc­tions that unlock the mouse.

dos instrucciones en c# que desbloquean el cursor del mouse y lo desbloquean
Fig. 26: The two select­ed instruc­tions unlock the cur­sor and make it visible.

Then we go to the Game­Con­trol Script and paste these instruc­tions at the end of the endGame method that will run when the time runs out.

script c sharp para unity 3d metodo placePlayerRandomly para colocar al jugador aleatoriamente en el escenario
Fig. 27: Paste the instruc­tions at the end of the endGame method.

End the game

We are also going to give the user the pos­si­bil­i­ty to end the game when­ev­er he wants by using the Escape key.

We do this with the GetKey­Down method of the Input class.

In the first video of Unity's fun­da­men­tal series, I explain how to read key­board and mouse entries, plus the dif­fer­ence between the dif­fer­ent meth­ods, there is also an arti­cle about the video on this page.

script c sharp unity 3d metodos update y startGame
Fig. 28: Exe­cute the endGame method by press­ing the escape key.

Conclusion

In the arti­cle we dis­cuss how to pro­gram the inter­ac­tion between the user inter­face ele­ments and the Game­Con­trol Script.

In the case of the but­ton the func­tion­al­i­ty is already pro­grammed for it to exe­cute meth­ods of the Scripts, but we must make sure that these meth­ods have pub­lic visibility.

Scroll to Top
Secured By miniOrange