Full text
Design and Development of an Online Multiplayer Videogame Adrián Mon Maroto Final Degree Work Bachelor’s Degree in Video Game Design and Development Universitat Jaume I July 3, 2023 Supervised by: Carlos González Ballester, PhD.
Acknowledgments First of all, I would like to thank my family and friends for their support and help in developing and testing my Final Degree Work. I also would like to thank my Final Degree Work supervisor, Carlos González Ballester, PhD, for helping me to decide the topic of this work and for his support and recommendations whenever I got stuck. And I would like to thank Sergio Barrachina Mir and José Vte. Martí Avilés for their inspiring LaTeX template for writing the Final Degree Work report, which I have used as a starting point in writing this report. i
Abstract This document presents a video game called Fixing It, which is a multiplayer and arcade game where the player takes control of a mechanic and together with his/her co-workers, the other players in the game, he/she must fix as many objects as possible before his working day is over. This document consists in the development of a multiplayer video game developed with Unity3D and focused for Windows. This has been done exploring the new Unity´s Netcode library next to the Unity´s Lobby and Relay libraries to create a lobby system and using this in turn to create an online mini-game. In addition to this, the Observer Pattern is used throughout the development of the project in order to allow a more orderly and independent programming and is used to separate the UI logic from the internal logic of the game. iii
Keywords Unity Multiplayer Lobby Observer Pattern v
Contents Contents vii 1 Introduction 1 1.1 WorkMotivation................................ 1 1.2 Objectives.................................... 3 1.3 Environment and Initial State . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 Planning and resources evaluation 5 2.1 Planning..................................... 5 2.2 ResourceEvaluation .............................. 6 3 Game Design Document 9 3.1 Conceptualization ............................... 9 3.2 Demography .................................. 10 3.3 Rules....................................... 11 3.4 Mechanics.................................... 12 3.5 InputInterface ................................. 17 3.6 Userinterface.................................. 18 3.7 Leveldesign................................... 22 3.8 Story....................................... 23 3.9 ArtStyle .................................... 23 3.10Soundtrack ................................... 24 3.11Multiplayer ................................... 24 4 Work Development and Results 25 4.1 WorkDevelopment............................... 25 4.2 Results...................................... 40 5 Conclusions and Future Work 43 5.1 Conclusions................................... 43 5.2 Futurework................................... 44 Bibliography 45 vii
6 Planning and resources evaluation Relay system to allow you to connect to a host by its IP and port; or to be the host and open a port. •Creation of the mini-game (50 hours): Create the game mechanics based on those of the GDD and merge them to create a demo level. •Adaptation of the mini-game to multiplayer (74 hours): Use the new Unity’s Netcode for GameObjects library to dynamically synchronise and/or clone instantiated objects across all users in the game session. Such as player prefabs or objects that later in the game will be used by all people and need their positions and internal states to be updated for everyone. •Writing the final report (20hours): Write the report, find images to link to it and correct minor errors in the file. •Preparation of FDW presentation (10 hours): Prepare the slides used in the final presentation and an accompanying script. The division of tasks can be seen in Figure 2.1 2.2 Resource Evaluation The resources used for this project were: •Electricity: Calculating the 300 hours worked and the use of a MSI GL63 8SD as a professional computer, with an average consumption of 180W and the average cost of electricity during the months of March, April, May and June, we estimate an electricity cost of around 4.32€. •Salary: Also based on the salary of a junior software programmer in Spain, which is around 10-12€per hour, it would have cost around 3300€. •Unity license: Free of charge due to educational licensing. •Visual Studio 2022: Free of charge since the Community version has been used. •Krita: Free of charge due to is an Open Source tool. •Blender: Free of charge due to is an Open Source tool. •External assets: All of the external assets used in this project were free assets. All these results in the sum of 3304.32€as the costs of all the work.
2.2. Resource Evaluation 7 Figure 2.1: Gantt chart (made with lucid)
Chapter 3 Game Design Document Contents 3.1 Conceptualization ............................. 9 3.2 Demography ................................ 10 3.3 Rules .................................... 11 3.4 Mechanics ................................. 12 3.5 InputInterface............................... 17 3.6 Userinterface ............................... 18 3.7 Leveldesign ................................ 22 3.8 Story .................................... 23 3.9 ArtStyle.................................. 23 3.10 Soundtrack................................. 24 3.11 Multiplayer................................. 24 3.1 Conceptualization Title: Fixing It Platforms: Windows Game Summary: This game will be placed in a level that simulates a mechanical workshop where the players work. They have to fix objects that NPCs will bring to the workshop because they are broken. To do so, they will have to collect the necessary pieces scattered in different parts of the room to craft the tools, which will break after a set number of uses, and use them to fix the objects. 9
10 Game Design Document Similar Games: A game with a similar gameplay could be Overcooked. Figure 3.1: Overcooked gameplay 3.2 Demography Age: Due to its future cute graphics and its absence of swear words and explicit elements this game is a game suitable for any player over 3 years of age. Although its complexity in coordinating with your peers and understanding what is going on, it is a game aimed at a slightly more logical thinking audience, ranging from pre-teens to young adults. Genre: The game can be classified into three distinct genres: Arcade due to being designed in such a way that the player can jump in, have a couple of quick games and leave; Puzzle as the player must use a bit of logic to think of the most efficient way to fix the objects in the limited time; and Multiplayer as it is a game with the ability to connect with up to 3 people online to play together for the highest score. Types of players: This game is for 2 types of players: casual gamers who simply want to unwind for half an hour a day and have a couple of quick games with their friends; and competitive gamers who will compete to get the highest possible scores in the game.
3.3. Rules 11 3.3 Rules 3.3.1 Design decisions Objective: The main objective of the game is to fix as many objects as possible in the given time. Difficulty: The difficulty of the game depends on the player. A novice player will not know the recipes for the tools so he will have to spend time going to the recipe book, i.e. he will have less time to fix items and it will be more difficult to get a high score. Meanwhile, an experienced player will be able to skip the step of looking at the recipe book, making it easier to get a high score. Variety: This first version of the game will have only 3 objects to fix with a total of 3 tools and 5 different pieces. This has been designed to have a minimum to test the mechanics of the game and see if they are fun to keep expanding it or not. Complexity: The only complexities for the players will be to be aware of which ojbect to fix is for which NPC; to be aware of the remaining uses of each tool before it breaks; and to manage the space available in the room for the pieces, tools and objects to fix. Limits: The only limit is spatial, the player will not be able to leave his working room. 3.3.2 Modifiable rules Before starting the mini-game, players can choose the colour of their character from a list of pre-set colours, as long as that colour is not chosen by another player. 3.3.3 Operational rules The player will be able to do a total of 3 different actions: •The player controls a character that can move along the XZ axes. •The character can grab or release one of the different types of objects at a time when he is at a minimum distance away from the counter containing the object. •The character can also interact at the same distance with the counters for a special use. This allows them to create tools, review crafting recipes or fix broken objects.
12 Game Design Document 3.3.4 Foundational rules These are the technical rules that spicify the behaviours of the operational rules: •The players will have a constant speed moveSpeed which will allow them to move around the room. This movement will in turn rotate the character on the Y-axis at a constant rotationSpeed to align it with the direction it is moving in. •When interacting with objects of any type to grab or release objects or to perform alternate interaction, a raycast will be launched from the base of the controlled character in the direction the character is facing and will have a range of interact- Distance. If a collision with any type of counter occurs, the counter will internally decide what action to take. 3.3.5 Written rules There will be an optional menu in the main menu called Controls, where the player can see the different controls to understand how to play. 3.3.6 Advisory rules The counters will show a local outline, i.e. they will only be displayed to the player who is playing rather than to the entire gaming room, which will be displayed when the player is inside interactDistance to indicate that they will interact with that object. 3.4 Mechanics 3.4.1 Actions •Movement: The player will have a static camera that will show the whole level. He/She can move across the XZ axes in the level and the character will turn to face that direction. •Grab/Release objects: When the character is facing a counter and inside a minimum range, it can grab the object that is on that counter only if it is not grabbing another object. At the same time it can release the object onto that counter only if the counter does not contains an object. •Craft objects: The player has to release from 1 to 3 pieces in the Tool Counter. After doing it he/she can do the alternate interaction to let the Tool Counter do the crafting logic. If the objects in the tool counter belong to a recipe the Tool Counter will output the tool onto itself so the character can grab it. •Fix objects: An object to fix needs to be onto some counter. After that if a controlled character tries to alternate interact with that counter it will check if he/she has one of the correct tools that the broken object needs to be fixed. If
3.4. Mechanics 13 that happens, the tool will be used and will check if it has more uses or if it will broke and disappear. If the object to fix does not need more tools, it will be ready to return to the NPC that asked about the repair. •Check recipe book: The recipe book is on another special counter, so the player needs to alternate interact with it. The first column will show an image of the object to be created and the second, third and fourth columns of each page will show an image of the objects to be fixed. If the level has more tools than the possible ones to be shown in the 2 pages of the book, the interface will show the user buttons to go to the next or previous page and see the rest of the recipes. See Figure 3.3. Figure 3.2: Recipe Book Figure 3.3: Recipe Book with a third page
14 Game Design Document 3.4.2 Entities •Pieces: One of the different objects that the player can grab or release. It is used to craft tools in the ToolCreatorCounter. •Tools: The second type of object that the player can grab or release. It is used fix the objects to fix and can break after a certain number of uses. •Objects to Fix: The last type of object that the player can grab or release. It is left by an NPC at the CustomerCounter for the player to pick up and fix using the necessary tools, these are shown above it with the pictorial representation of the tools. Figure 3.4: Object to Fix in CustomerCounter •NPC: They are the customers who give the Objects to Fix to the CustomerCounters so the player gan grab and fix them. •TableCounter: An empty counter where the player can grab or release objects and try to fix the objects that are on it. See Figure 3.5 •ToolCreatorCounter: A counter where the player can release up to 3 pieces and an alternate interact will consume those objects to try to create a tool. If the combination of those objects returns a tool, it will be created and ready to be grabbed by a player. See Figure 3.6 •CustomerCounter: A counter where a NPC will be waiting for a player to return its fixed item. In case there is no NPC assigned to this counter yet, it will be useless. See Figure 3.7
3.4. Mechanics 15 •PiecesCounter: Every time a player tries to interact with it while not grabbing an object, the counter will generate the piece related to itself and give it to the player. See Figure 3.8 •ManualCounter: A counter where the player can check the recipes of the tools after doing an alternate interaction. See Figure 3.9 Figure 3.5: TableCounter with a piece on top Figure 3.6: ToolCreatorCounter ready to create a tool
22 Game Design Document 3.7 Level design The prototype level of the game is as shown in the following image. Figure 3.17: Level Design
3.8. Story 23 3.8 Story This game will have no story due to the fact that it is a prototype. But in case it will be wanted to be expanded, the story could be related to a group of mechanics who make a repair shop and as they become famous in the village they get more and more things to fix. As they gain popularity, their workload increases with more complex repairs. The mechanics’ skills and dedication become renowned, attracting customers from far and wide. 3.9 Art Style Placeholders will be used in the first instance and if time permits, they will be replaced by Simplistic Low-poly approach, taking inspiration on games such as Overcooked, also implementing Unity Store Assets and maybe assets created by. The final artwork will be added in future versions of the game, for the final prototype placeholders have been used. Figure 3.18: Reference Art 0 Figure 3.19: Reference Art 1
24 Game Design Document 3.10 Soundtrack 3.10.1 Sound Effects There will be small sound effects for when a tool is used or an item is fixed; when a tool is created; the customer receives their fixed item; any of the PiecesCounter in the level is used; a tool is broken; a Customer is moving; or for when the player character is moving. 3.10.2 Music The music will be a bit fast to give the player even more of a time trial feeling when playing the mini-game. 3.11 Multiplayer Up to 4 players per game will be able to connect online, each player having a different character colour. Players will not be able to interact with each other with any direct action. What they will be able to do is to annoy each other with their collisions, thus generating situations where the gameplay changes as the characters become a moving wall for the other players.
Chapter 4 Work Development and Results Contents 4.1 WorkDevelopment ............................ 25 4.2 Results ................................... 40 This chapter is going to explain how everything was developed and if anything has changed from the initial planning will be detailed and justified. 4.1 Work Development This section explains the most relevant aspects of the developed work following the same order as shown in Figure 2.1 in the Planning. 4.1.1 Overview The overall project follows a very similar structure. The Observer Pattern has been followed in order to create a clean and independent code architecture. For this, we have decided to use the Scriptable Objects 1offered by Unity as a bridge between the observed object and the different observers, thus generating a layer of abstraction that would allow changing any side of the bridge without the other side being aware of anything, this system of using Scriptable Objects as bridges has been inspired by Unity’s Open Project [10]. In addition, Unity’s Assembly definitions 2have been used to ensure that within the code dependencies, there are no dependencies in loops and at the same time to increase 1Go to A.2 to see the definition of a Scriptable Object 2Go to A.3 to see the definition of the Assembly Definition 25
26 Work Development and Results the compilation times of the code, The basic understanding of how to use them was provided by channels such as Infallible Code [2].
4.1. Work Development 27 The game has been designed in a way that there will always be at least 2 active scenes: •LocalPersistentManagers: A scene where all the local managers, such as the SceneLoaderManager, the AudioManager or the InputController, will be located. It will also have a canvas which will be displayed while downloading and loading other scenes. •GameScene: It will be the scene which will be replaced according to the scene we want the player to see. Depending on the moment of the game it can be the Main Menu scene, the Lobby Selection scene, the CharacterSelection scene or the Minigame scene. 4.1.2 Scene Loader The first thing that was not originally planned was to make a SceneLoaderManager 3and to apply for the first time the Observer Pattern with the Scriptable Objects as bridges, which was necessary when programming everything and seeing that at least 2 active scenes were needed simultaneously. The very first thing we needed to do was to create our bridge system using Scriptable Objects. To do this we created a script with an abstract class which would contain a UnityAction<T> and a public function that would receive a parameter of type T and would invoke the UnityAction in case it has subscribed functions. 4 We also create another new script for the UnityActions that do not receive any parameter instead of creating a child class because T cannot be void. 5 Once this was done we designed how the GameScene loading and unloading system works. There is a GameObject called ChangeSceneBridge inside LocalPersistentManagers that is in charge of listening to those VoidEventChannelSO that invoke its UnityAction and have been created to notify that you want to change scene. When its private functions are called by those events, this script is in charge of invoking the UnityAction of the corresponding LoadSceneChannelSO. LoadSceneChannelSO is a script that inherits from BaseEventChannelSO<T> which has set GameSceneSO as T, a subtype of ScriptableObject created for the project that has as its only parameter an AssetReference and will be used as a scene reference. These last UnityAction are listened by the SceneLoaderManager, another GameObject inside LocalPersistentManagers, and because it receives as parameter a GameSceneSO the SceneLoaderManager will load its AssetReference as new GameScene of the game and in turn it will unload the previous GameScene and it will decide according to the LoadSceneChannelSO that has sent the event whether to load it as local scene or as multiplayer scene. 3Go to B.4 to see how the SceneLoaderManager is implemented 4Go to B.1 to see how the asbtract class is implemented 5Go to B.2 to see how the VoidEventChannelSO is implemented
28 Work Development and Results In case the SceneLoaderManager decides to load multiplayer, the loading logic will be delegated through a StringBoolFuncSO, another bridge system created from Scriptable Objects in which instead of invoking UnityAction a Func is invoked where one side of the bridge assigns the desired function to the Func and the other side invokes that function 6, so that a script called NetworkSceneLoader 7is in charge of carrying all the logic of the loading and unloading of the multiplayer scenes. When starting to load and when finishing loading the scenes it will invoke 2 different VoidEventChannelSOs, one for each moment, which will be listened by the Canvas located in LocalPersistentManagers to show a loading screen while everything is happening. Once everything has been prepared, it is decided that the game will start with a scene called Initialisation, in charge of loading LocalPersistentManagers asynchronously and when it detects that they are already loaded directly invoke the UnityAction of the LoadSceneChannelSO, which is to load locally with parameter the GameSceneSO with the reference of the MainMenu, and instantly unload Initialisation asynchronously. In this case it has been decided to call directly the LoadSceneChannelSO instead of a VoidEventChannelSO that is listened by the ChangeSceneBridge because this last one was created as a bridge between the different GameObjects that want to change scene and the SceneLoaderManager because when splitting the code with the assemblies definitions of Unity we realised that to use the LoadSceneChannelSO it was necessary to have the reference of the GameSceneSO, which GameObjects in general don’t seem to need to have. On the other hand, the Initialisation scene code does it directly because due to its operation it was decided to group it with the rest of the codes in charge of handling scenes, so they are in the same assembly definition and can use the LoadSceneChannelSO without problems. The SceneLoaderManager is also in charge of closing the game. Figure 4.1: Relationship diagram of the scene loading 6Go to B.3 to see how the base abstract class for FuncSO is implemented 7Go to B.5 to see how the NetworkSceneLoader is implemented
4.1. Work Development 29 4.1.3 Main Menu It is a simple menu where the player can decide to exit the game; enter in the options menu and change the screen or volume settings; or play the game. The first thing to do was to make a simple user interface design to reflect all actions. For this we created a canvas with 4 different panels: •Main Menu Panel: It has Play, Options and Exit buttons. See Figure 3.11. •Options Panel: It has Screen, Volume and Back buttons. See Figure 3.12. •Screen Settings Panel: It has a dropdown with all the Screen Resolutions; a Fullscreen toggle; and Accept and Reset Buttons. See Figure 3.13. •Audio Settings Panel: It has General Volume, Music and Sound Sliders. See Figure 3.14. Once all the UI design was done and animated using a LeanTween library [1], we proceeded to make all the logic of it following the Observer Pattern and separating the logic of the UI from the internal logic. Visual Logic The first thing I did was to create a custom script for each panel which would have referenced all the objects on the panel: buttons, sliders... Then I added to these referenced objects that after being used by the user would invoke one of our custom Scriptable Objects. •Main Menu Panel: Its buttons would each invoke a VoidEventChannelSO. •Options Menu Panel: Its buttons would also invoke a VoidEventChannelSO. •Screen Settings Panel: Only the Accept and Cancel buttons are associated to a custom Scriptable Object but these needed to pass 2 arguments, the index of the chosen resolution and a boolean to indicate the full screen, so it was not possible to make a subclass of BaseEventChannelSO<T>, so it was decided to make a homonymous class but with 2 parameters called BaseEventChannelSO<T1,T2> 8 and then make a subclass of it which would have as T1 an int and as T2 a bool, called ScreenSettingsChannelSO. •Audio Settings Panel: Its 3 sliders invoke FloatEventChannelSO, subclass of BaseEventChannelSO<T> that have as T a float, and pass the values of the sliders as argument of the event. Once all the panel scripts have been created a Canvas script was created to handle all the internal animations and which Panels will be displayed or disabled. 8Go to B.1 to see how BaseEventChannelSO<T1,T2> is implemented
30 Work Development and Results Internal Logic •Main Menu Panel: –Play Button: The VoidEventChannelSO invoked by this button is listened by the ChangeSceneBridge, which is already internally in charge of invoking the LoadSceneChannelSO listened by the SceneLoaderManager to load the LobbySelection scene as the GameScene locally. –Options Button: The VoidEventChannelSO invoked by this button is listened by the Canvas and it is in charge of making the animation to show the Options Menu Panel and to hide and deactivate the Main Menu Panel. –Exit Button: The VoidEventChannelSO invoked by this button is listened by the SceneLoaderManager and it closes the game. •Options Menu Panel: The VoidEventChannelSOs invoked by each button are listened by the Canvas to display the Screen Settings Panel, Volume Settings Panel and to re-display the Main Menu Panel respectively. •Screen Settings Panel: Both Accept and Cancel buttons invoke the same ScreenSettingsChannelSO but with different parameters, the first button gets the index of the current item in the dropdown and the gets if the toggle is On or not while the second button send the maximum resolution index and a true. The event is listened by another gameobject called ResolutionManager, which has a script that manages the resolution and whether it is in fullscreen, and resizes the game view. •Audio Settings Panel:The FloatEventChannelSOs invoked by each Slider are listened by the AudioManager, a gameobject inside LocalPersistentManagers designed to control the sound channels and the music that is currently playing. A demostration video of the Main Menu: MainMenu Demo Video 4.1.4 Lobby and Relay System To do this, a scene called LobbySelection has been created. Here the player will be in a menu where they can change their player name, choose whether to create a lobby, join one of the public lobbies, join a private lobby via code or return to the Main Menu. As with the Main Menu, the first thing that was done was to design a UI, which can be organised in 4 different parts, see Figure 3.15: •PlayerNameInputField: It is just an InputField where the player can modify his/her online name.
4.1. Work Development 31 •LobbiesScrollArea Panel: It has a button within a vertical group that acts as a template join button to be duplicated when new public lobbies are detected, it also has a text to indicate that there are no public lobbies at the moment. •Lobby Options Panel: It has the Create Lobby, Join by Code, Refresh Lobbies and To Main Menu buttons. •PopUp Panel: Panel that internally has 4 panels: the CreateLobby Panel, Join- ByCode Panel, LobbyErrorPanel and LobbyState Panel. And as in the Main Menu, it was decided to separate the internal logic from the UI logic by using the Observer Pattern. Visual Logic The same structure as in the Main Menu has been followed again: create a script for each panel with references to its objects and also that these objects, when used, invoke the corresponding customs Scriptable Objects. A script has also been made for the current canvas to act as a manager for all panels, it listens all the necesarry events from our customs Scriptable Objects to update or set the values or the visibility of the panels. •PlayerNameInputField: Being an object with nothing internally in charge of it, its logic has been delegated to the Canvas. Each time its value is changed it invokes a StringEventChannelSO, another subclass of BaseEventChannelSO<T> with a string as T, passing as parameter its new value. •LobbiesScrollArea Panel: Listens for a LobbiesChannelSO, another subclass of BaseEventChannelSO<T> that uses List<Lobby> as T, and when that LobbiesChannelSO is invoked causes this panel to receive all available public lists; turns on or off the message that no public lobbies are available depending on the size of the list received; and all dynamically generated buttons to join lobbies are destroyed and new ones are generated based on the lobbies in the list received. In addition, dynamically generated lobby join buttons display the lobby name, the number of people in the lobby and the maximum number of people at the time the button is created. It also internally stores the lobby reference so that when it is pressed it invokes a StringEventChannelSO passing the lobby ID as a parameter. •Lobby Options Panel: Each button invokes a VoidEventChannelSO. •PopUp Panel: Panel that acts as a manager for each of the possible PopUps that may appear in this scene. –CreateLobby Panel: Its Create button invokes a CreateLobbyChannelSO, a subclass of BaseEventChannelSO<T1,T2> and uses a string as T1 and a bool as T2, in which it passes as parameters the name chosen for the lobby and
38 Work Development and Results 4.1.6 Mini-game A scene was created that will contain the mini-game. First of all, all the mechanics and their relationships at the single player level were thought out. The mini-game has used the Observer Pattern along with creating Components. This has been done because there are certain things that don’t make sense to put that layer of abstraction because of its direct relationship, like the character and the sounds or particles it generates, it knows when to make sound or when to activate its particle system. FixingGameManager It is the manager of the level logic 13. It is in charge of managing the activation and deactivation of the player input or changing the Input channel from Gameplay to Menu mode and vice versa; has a Scriptable Object with the recipes that the level will use and then the objects that need it will get it through a ToolRecipeManagerFuncSO, subclass of BaseFuncSO<TResult> that uses a ToolRecipeManagerSO as T, which in turn is a Scriptable Object where an array with the tool crafting recipes is stored; where to spawn the NPCs, which Object to Fix with and which counter to go to; and the game state. Room Objects They are part of the main mechanics of the game 14 . They are divided according to a number into 3 different types: Pieces, Tools and Objects To Fix. They have 2 AudioComponent, Component programmed in order to run a sound clip on a specific channel, one for when the object is used and one for when the object breaks. Although in reality they are only used by the Tools. They have a reference to an IRoomObjectParent 15 , an interface designed for all those gameobjects that will be able to handle RoomObjects, which will be their parent in the hierarchy of objects in the scene and this IRoomObjectParent in turn has a reference to the RoomObject. it has a static function that is in charge of spawning new RoomObjects in an IRoomObjectParent. For the Object to Fix a subclass 16 has been created because it needs to recycle all the logic of the RoomObject but adding an array indicating the tools needed to fix the object and another array to take into account the tools already used. 13Go to B.10 to see the implementation 14Go to B.11 to see the implementation of RoomObject 15Go to B.12 to see the implementation of IRoomObjectParent 16Go to B.13 to see the implementation of the Object To Fix subclass, it is called ToFixRoomObject
4.1. Work Development 39 To show the user the tools he/she needs to use, a component has been created for the Object to Fix that is in charge of showing the image representation of the tools to be used on top of the object. See Figure 3.4. Player Gameobject in charge of moving; rotating; acting as IRoomObjectParent; and handling the interactions that the player can perform with the different types of counter, calling the BaseCounter and this is in charge of inheriting the behaviour of the interaction 17. It has 2 components in charge of the animation of the player and the walking sound. And the gameobject has a particle system that is activated by the character’s movement. Counters They are a group of different objects which are also necessary for the game. They all have a common parent class, BaseCounter 18, which each Counter overrides to implement its functionality. There are a total of 5 different Counters and all of them act as IRoomObjectParent. It is possible to see all of them in the subsection 3.4.2. NPCs The code that controls them is CustomerController 19 and its internal logic is a hardcoded state machine because it is the only place in the project where one would be required. It also acts as IRoomObjectParent. As can be seen in the figure 4.6 it can be seen that the first thing the NPC does is to go to a Counter, once there he waits until the broken object he had taken to fix is returned to him and when he has finished he leaves to leave the Counter for the next NPC. Figure 4.6: NPCs State Machine 4.1.7 Adaption of the mini-game to multiplayer To modify the mini-game logic from singleplayer to multiplayer mode what has been done has been: 17Go to B.14 to see how the Player Controller is implemented 18Go to B.15 to see how the BaseCounter is implemented 19Go to B.16 to see how the CustomerController is implemented
40 Work Development and Results •NetworkVariables and NetworkLists: Variables and lists which are synchronised between all users. They are used for important things like the number of uses of a tool or the remaining tools that an ObjectToFix needs. •ServerRpc and ClientRpc functions: These are functions that run on the server and on the clients respectively. When a client tries to perform an action, it usually calls a ServerRpc function so that the server executes all the internal logic and when it is finished, it calls a ClientRpc function so that all the clients receive the corresponding visual changes. •Network events: Events that NetworkVariables and NetworkLists have which are executed every time their values have been changed. There are certain parts of the code where this has been chosen instead of the ServerRpc and ClientRpc in order to avoid synchronisation failures of these NetworkVariables when calling the ClientRpc. 4.1.8 Extra There are 3 things that have been done as extras to all of this: •Centralise the Input System with a Scriptable Object: To do this Unity’s new Input System have been used and it was created a code called InputReaderSO 20 which is a Scriptable Object that anyone can access and has the designated functions and events to control all the game’s Input. •Centralising the colours of UI elements: A Scriptable Object was created which contains the set of colours that any UI element has. After this, a code called SelectableUIData 21 was created which would be in charge of assigning the colours of the Scriptable Object to the elements that contain this code, thus allowing a centralisation of the colours and an ease of design. •Put the more generic codes in a separate folder to start creating a library: As codes have been created that are tools for programming or design, I have decided to separate them in a separate folder called ProgramadorCastellano. This is because they are codes that can be improved and used in the future as a custom library. Inside would be codes such as BaseEventChannelSO or SelectableUIData. 4.2 Results Although Unity’s new multiplayer library is still buggy, a first version of a videogame has been created following the Observer Pattern as much as possible and it is playable by up to 4 simultaneous players in a single lobby, who can enjoy short 2-minute games. 20Go to B.17 to see how the InputReaderSO is implemented 21Go to B.18 to see how the SelectableUIData is implemented
4.2. Results 41 From a computer science point of view, the separate codes in the ProgramadorCastellano folder can serve as a library for any programmer who wants to create an Observer Pattern. Also due to the separation of interface and logic codes anyone who wants to recreate the lobbies system can use the codes already created for this project without having to modify it for the most part.
Chapter 5 Conclusions and Future Work Contents 5.1 Conclusions ................................ 43 5.2 Futurework ................................ 44 In this chapter, the conclusions of the work, as well as its future extensions are shown. 5.1 Conclusions It was a challenge to make a multiplayer game with a design pattern applied to it. This is because we have never dealt with anything related to multiplayer games in our career, nor have we ever put into practice the use of design patterns when organising code. Also the use of a new library has resulted in more difficulties in the development of the project. Synchronisation errors of certain objects that could only be fixed by converting them to Singletons, even though this was not originally intended, that certain objects shared their NetworkObject ID so that the value had to be re-assigned by hand, or that when loading scenes asynchronously, clients could not disconnect correctly due to an internal bug in the library, causing the user to have to disconnect by brute force with all the problems that this entails. So to develop a game of any kind with a new library I recommend waiting a bit until it is more developed and does not have major bugs like those mentioned above. 43
44 Conclusions and Future Work 5.2 Future work As future work the idea would be to wait a little while for the Unity multiplayer library bugs to be fixed. Once there are no major bugs we would continue with the progress of the game to redo the asynchronous download of the clients without crashing, add visual and sound details to the game, take advantage of the Observer Pattern to make a system of achievements without too much difficulty and study about level design to make different levels with different tools and objects to fix so that there is more variety and therefore fun for the end player. Regarding the more abstract codes stored in the ProgramadorCastellano folder the idea is to refine and extend those codes to generate a public library to have all the primitive BaseEventSO and BaseFuncSO ready to use just by downloading the folder and also to have a central modification system of the UI that allows apart from changing the colours, to change the images or the animations of the UI in a centralised way.
Bibliography [1] LeanTween - LeanTween. [2] Infallible Code. Before you continue to YouTube. [3] Code Monkey. Before you continue to YouTube. [4] Tarodev. Before you continue to YouTube. [5] Unity Technologies. Unity - Manual: Assembly definitions. [6] Unity Technologies. Unity - Manual: ScriptableObject. [7] Unity Technologies. Unity Lobby Service. [8] Unity Technologies. Unity Relay. [9] Unity Technologies. About Netcode for GameObjects | Unity Multiplayer Networking, 6 2023. [10] Unity. Bringing characters to life with animation | Open Projects Devlog, 5 2021. [11] Wikipedia contributors. Observer pattern — Wikipedia, the free encyclopedia, 2023. 45
A p p e n d i x A Glossary A.1 Observer Pattern “In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is often used for implementing distributed event-handling systems in event-driven software. In such systems, the subject is usually named a "stream of events" or "stream source of events" while the observers are called "sinks of events." The stream nomenclature alludes to a physical setup in which the observers are physically separated and have no control over the emitted events from the subject/stream source. This pattern thus suits any process by which data arrives from some input that is not available to the CPU at startup, but instead arrives seemingly at random (HTTP requests, GPIO data, user input from peripherals, distributed databases and blockchains, etc.). Most modern programming languages comprise built-in event constructs implementing the observer-pattern components. While not mandatory, most observer implementations use background threads listening for subject events and other support mechanisms provided by the kernel.” [11] A.2 Scriptable Object “A ScriptableObject is a data container that you can use to save large amounts of data, independent of class instances.” [6] 47
54 Source code 1using FixingIt.Events; 2using FixingIt.SceneManagement.ScriptableObjects; 3using ProgramadorCastellano.Events; 4using ProgramadorCastellano.Funcs; 5using System; 6using UnityEngine; 7using UnityEngine.ResourceManagement.AsyncOperations; 8using UnityEngine.ResourceManagement.ResourceProviders; 9using UnityEngine.SceneManagement; 10 11 namespace FixingIt.SceneManagement.Logic 12 { 13 /// <summary> 14 /// Persistent Manager, doesnt need an Instance or to clear the funcs 15 /// </summary> 16 public class SceneLoaderManager : MonoBehaviour 17 { 18 // filled after loaded one scene 19 private GameSceneSO _sceneToLoad; 20 private GameSceneSO _currentSceneLoaded; 21 private bool _isSceneToLoadNetwork = false; 22 private bool _isCurrentSceneNetwork = false; 23 24 private float _necessaryWaitSeconds = 0.1f; 25 26 [Header("Listening To")] 27 [SerializeField] 28 private LoadSceneChannelSO _loadSceneChannel; 29 [SerializeField] 30 private LoadSceneChannelSO _loadNetworkSceneChannel; 31 [SerializeField] 32 private VoidEventChannelSO _exitGameEvent; 33 [SerializeField] 34 private VoidEventChannelSO _unloadedNetworkEventCompleted; 35 36 [Header("Broadcasting To")] 37 [SerializeField] VoidEventChannelSO _startSceneLoadingEvent; 38 [SerializeField] VoidEventChannelSO _sceneLoadedEvent; 39 40 [Header("Invoking Func")] 41 [SerializeField] 42 private StringBoolFuncSO _loadNewNetworkSceneByNameFunc; 43 [SerializeField] 44 private StringBoolFuncSO _unloadNetworkSceneByNameFunc; 45 46 [Header("Setting Func")] 47 [SerializeField] 48 private StringFuncSO _getCurrentSceneNameFunc; 49 50 private void Awake() 51 {
B.4. SceneLoaderManager 55 52 //DontDestroyOnLoad(gameObject); 53 54 _getCurrentSceneNameFunc.TrySetOnFuncRaised(() => _currentSceneLoaded.name); 55 } 56 57 private void OnEnable() 58 { 59 _loadSceneChannel.OnEventRaised += LoadScene; 60 _loadNetworkSceneChannel.OnEventRaised += LoadNetworkScene; 61 _exitGameEvent.OnEventRaised += ExitGame; 62 63 _unloadedNetworkEventCompleted.OnEventRaised += SceneLoaderManager_UnloadedNetworkEventCompleted; 64 } 65 66 private void OnDisable() 67 { 68 _loadSceneChannel.OnEventRaised -= LoadScene; 69 _loadNetworkSceneChannel.OnEventRaised -= LoadNetworkScene; 70 _exitGameEvent.OnEventRaised -= ExitGame; 71 72 _unloadedNetworkEventCompleted.OnEventRaised -= SceneLoaderManager_UnloadedNetworkEventCompleted; 73 } 74 75 #region Local Load 76 private void LoadScene(GameSceneSO sceneToLoad) 77 { 78 // send event 79 _startSceneLoadingEvent.RaiseEvent(); 80 81 _sceneToLoad = sceneToLoad; 82 _isSceneToLoadNetwork = false; 83 84 UnloadPreviousScene(); 85 LoadNewScene(); 86 } 87 88 private void LoadNewScene() 89 { 90 // load scene 91 var loadingOperationHandle = _sceneToLoad.SceneReference.LoadSceneAsync(LoadSceneMode.Additive); 92 loadingOperationHandle.Completed += OnNewSceneLoaded; 93 94 _isCurrentSceneNetwork = false; 95 } 96 97 private void OnNewSceneLoaded(AsyncOperationHandle<SceneInstance> obj) 98 { 99 _currentSceneLoaded = _sceneToLoad; 100 101 Scene s = obj.Result.Scene; 102 SceneManager.SetActiveScene(s);
56 Source code 103 104 //LightProbes.TetrahedralizeAsync(); //not necessary 105 106 // send event 107 _sceneLoadedEvent.RaiseEvent(); 108 } 109 #endregion 110 111 #region Network Load 112 private void LoadNetworkScene(GameSceneSO sceneToLoad) 113 { 114 // send event 115 _startSceneLoadingEvent.RaiseEvent(); 116 117 _sceneToLoad = sceneToLoad; 118 _isSceneToLoadNetwork = true; 119 120 UnloadPreviousScene(); 121 122 // si hemos descargado una local 123 if (!_isCurrentSceneNetwork) 124 { 125 Invoke(nameof(LoadNewNetworkScene), _necessaryWaitSeconds); // necessary wait to prevent errors 126 } 127 // else => lo maneja UnloadPreviousSceneNetwork 128 } 129 130 /// <summary> 131 /// Function that should be called after all the clients have unload async the previous networkScene 132 /// </summary> 133 private void LoadNewNetworkScene() 134 { 135 // load scene 136 string sceneName = _sceneToLoad.name; 137 bool hasNetSceneLoaded = false; 138 try 139 { 140 hasNetSceneLoaded = _loadNewNetworkSceneByNameFunc.RaiseFunc(sceneName); 141 } 142 catch (Exception e) 143 { 144 ManageNetworkSceneLoaderExceptions(e); 145 } 146 147 if (hasNetSceneLoaded) 148 _currentSceneLoaded = _sceneToLoad; 149 150 _isCurrentSceneNetwork = hasNetSceneLoaded; 151 } 152 #endregion 153
B.4. SceneLoaderManager 57 154 #region Unload 155 /// <summary> 156 /// Se podra hacer Coroutine para a adir efecto de pantalla de carga 157 /// </summary> 158 private void UnloadPreviousScene() 159 { 160 // null when we are entering in the Main Menu 161 if (_currentSceneLoaded == null) 162 { 163 return; 164 } 165 166 // check if it is managed by SceneManager or by NetworkSceneManager 167 if (!_isCurrentSceneNetwork) 168 { 169 UnloadPreviousSceneLocal(); 170 } 171 else 172 { 173 UnloadPreviousSceneNetwork(); 174 } 175 } 176 177 private void UnloadPreviousSceneLocal() 178 { 179 _currentSceneLoaded.SceneReference.UnLoadScene(); 180 } 181 private void UnloadPreviousSceneNetwork() 182 { 183 string sceneName = _currentSceneLoaded.name; 184 185 try 186 { 187 _unloadNetworkSceneByNameFunc.RaiseFunc(sceneName); 188 } 189 catch (Exception e) 190 { 191 ManageNetworkSceneLoaderExceptions(e); 192 } 193 } 194 #endregion 195 196 private void ExitGame() 197 { 198 Debug.Log("Quitting Application!"); 199 Application.Quit(); 200 } 201 202 private void ManageNetworkSceneLoaderExceptions(Exception e) 203 { 204 Debug.LogError($"Error catched: {e.Message}");
58 Source code 205 } 206 207 private void SceneLoaderManager_UnloadedNetworkEventCompleted() 208 { 209 if (_isSceneToLoadNetwork) 210 { 211 Invoke(nameof(LoadNewNetworkScene), _necessaryWaitSeconds); // necessary wait to prevent errors 212 } 213 // else -> managed by its function 214 } 215 } 216 } B.5 NetworkSceneLoader 1using ProgramadorCastellano.Events; 2using ProgramadorCastellano.Funcs; 3using System; 4using Unity.Netcode; 5using UnityEngine; 6using UnityEngine.SceneManagement; 7 8namespace FixingIt.SceneManagement.Logic 9{ 10 public class NetworkSceneLoader : NetworkBehaviour 11 { 12 public static NetworkSceneLoader Instance { get; private set; } 13 14 [Header("Broadcasting To")] 15 [SerializeField] 16 private VoidEventChannelSO _sceneLoadedEvent; 17 [SerializeField] 18 private VoidEventChannelSO _unloadedNetworkSceneEventCompleted; 19 20 [Header("Setting Func")] 21 [SerializeField] 22 private StringBoolFuncSO _loadNewNetworkSceneByNameFunc; 23 [SerializeField] 24 private StringBoolFuncSO _unloadNetworkSceneByNameFunc; 25 26 private void Awake() 27 { 28 if (Instance != null && Instance != this) 29 { 30 Destroy(this); 31 } 32 else 33 {
B.5. NetworkSceneLoader 59 34 Instance = this; 35 DontDestroyOnLoad(this); 36 } 37 38 // clear funcs 39 _loadNewNetworkSceneByNameFunc.ClearOnFuncRaised(); 40 _unloadNetworkSceneByNameFunc.ClearOnFuncRaised(); 41 42 // set funcs 43 _loadNewNetworkSceneByNameFunc.TrySetOnFuncRaised(LoadNewNetworkScene); 44 _unloadNetworkSceneByNameFunc.TrySetOnFuncRaised(UnloadNetworkScene); 45 } 46 47 public override void OnNetworkSpawn() 48 { 49 if (IsServer) 50 { 51 NetworkManager.Singleton.SceneManager.OnSceneEvent += NetworkSceneLoader_OnNetworkSceneEvent; 52 } 53 Debug.Log($"OnNetworkSpawn and IsServer: {IsServer}"); 54 55 base.OnNetworkSpawn(); 56 } 57 58 #region Load 59 /// <summary> 60 /// Function that should be called after all the clients have unload async the previous networkScene. 61 /// Loads async a new NetworkScene 62 /// </summary> 63 /// <param name="sceneName">Name of the scene to load</param> 64 /// <returns>If the Scene was loaded && You are server</returns> 65 /// <exception cref="Exception">It was not possible to load the scene due to NetworkErrors</exception> 66 private bool LoadNewNetworkScene(string sceneName) 67 { 68 if (!IsServer) 69 return false; 70 71 var status = NetworkManager.Singleton.SceneManager.LoadScene(sceneName, LoadSceneMode.Additive); 72 if (status != SceneEventProgressStatus.Started) 73 { 74 string errorMsg = $"Failed to load {sceneName} with a {nameof(SceneEventProgressStatus)}: {status}"; 75 76 Debug.LogWarning(errorMsg); 77 throw new Exception(errorMsg); 78 } 79 80 return true; 81 } 82 #endregion 83 84 #region Unload
60 Source code 85 /// <summary> 86 /// Unloads a NetworkScene 87 /// </summary> 88 /// <param name="sceneName">Name of the scene to unload</param> 89 /// <returns>If the Scene was unloaded && You are server</returns> 90 /// <exception cref="Exception">It was not possible to unload the scene due to nameScene error</exception> 91 private bool UnloadNetworkScene(string sceneName) 92 { 93 // TODO: mirar esto bien 94 if (!IsServer) 95 return false; 96 97 Scene sceneToUnload = SceneManager.GetSceneByName(sceneName); 98 if (!sceneToUnload.IsValid()) 99 { 100 string errorMsg = $"UnloadingError: Escena con nombre {sceneName} no existe ahora mismo"; 101 102 Debug.LogWarning(errorMsg); 103 throw new Exception(errorMsg); 104 } 105 106 NetworkManager.Singleton.SceneManager.UnloadScene(sceneToUnload); 107 return true; 108 } 109 #endregion 110 111 private void NetworkSceneLoader_OnNetworkSceneEvent(SceneEvent sceneEvent) 112 { 113 var clientOrServer = sceneEvent.ClientId == NetworkManager.ServerClientId ? "server" : "client"; 114 switch (sceneEvent.SceneEventType) 115 { 116 // locally cases 117 case SceneEventType.LoadComplete: 118 { 119 //if (sceneEvent.ClientId == OwnerClientId) { 120 // SceneManager.SetActiveScene(sceneEvent.Scene); 121 //} 122 123 Debug.Log($"Loaded the {sceneEvent.SceneName} scene on {clientOrServer}-({sceneEvent.ClientId})."); 124 break; 125 } 126 case SceneEventType.UnloadComplete: 127 { 128 Debug.Log($"Unloaded the {sceneEvent.SceneName} scene on {clientOrServer}-({sceneEvent.ClientId})."); 129 break; 130 } 131 // when server && all clients 132 case SceneEventType.LoadEventCompleted: 133 { 134 Debug.Log($"Load event completed for the following client identifiers:({sceneEvent.ClientsThatCompleted})"); 135 if (sceneEvent.ClientsThatTimedOut.Count > 0)
B.6. FixingGameMultiplayer NOT FINAL VERSION 61 136 { 137 Debug.LogWarning($"Load event timed out for the following client identifiers:({sceneEvent.ClientsThatTimedOut})"); 138 } 139 140 // send event 141 _sceneLoadedEvent.RaiseEvent(); 142 break; 143 } 144 case SceneEventType.UnloadEventCompleted: 145 { 146 Debug.Log($"Unload event completed for the following client identifiers:({sceneEvent.ClientsThatCompleted})"); 147 if (sceneEvent.ClientsThatTimedOut.Count > 0) 148 { 149 Debug.LogWarning($"Unload event timed out for the following client identifiers:({sceneEvent.ClientsThatTimedOut})"); 150 } 151 152 // in theory this code is unreachable for clients but just in case 153 if (IsServer) 154 { 155 _unloadedNetworkSceneEventCompleted.RaiseEvent(); 156 } 157 158 break; 159 } 160 } 161 } 162 } 163 } B.6 FixingGameMultiplayer NOT FINAL VERSION 1using FixingIt.Events; 2using FixingIt.Funcs; 3using FixingIt.Minigame; 4using FixingIt.PlayerGame; 5using FixingIt.RoomObjects.Logic; 6using FixingIt.RoomObjects.SO; 7using FixingIt.SceneManagement.ScriptableObjects; 8using ProgramadorCastellano.Events; 9using ProgramadorCastellano.Funcs; 10 using System.Linq; 11 using Unity.Netcode; 12 using Unity.Services.Authentication; 13 using UnityEngine; 14 using UnityEngine.SceneManagement; 15 16 namespace FixingIt.Multiplayer 17 {
62 Source code 18 public class FixingGameMultiplayer : NetworkBehaviour 19 { 20 private const string PLAYER_PREFS_PLAYER_NAME_MULTIPLAYER = "PlayerNameMultiplayer"; 21 22 public static FixingGameMultiplayer Instance { get; private set; } 23 24 [SerializeField] private GameSceneSO _characterSelectionSceneSO; 25 [SerializeField] private Color[] _playerColorArray; 26 [SerializeField] private RoomObjectsSOListSO _allRoomObjectsSOListSO; 27 28 private NetworkList<PlayerData> _playerDataNetworkList; 29 private string _playerName; 30 31 [Header("Broadcasting To")] 32 [SerializeField] 33 private VoidEventChannelSO _hostStartedEvent; 34 [SerializeField] 35 private StringEventChannelSO _rejectedToServerEvent; 36 [SerializeField] 37 private VoidEventChannelSO _playerDataNetworkListChangedEvent; 38 [SerializeField] 39 private VoidEventChannelSO _networkToMainMenuEvent; 40 [SerializeField] 41 private StringEventChannelSO _playerIdDisconnectedEvent; 42 43 [Header("Listening To")] 44 [SerializeField] 45 private VoidEventChannelSO _lobbyCreatedEvent; 46 [SerializeField] 47 private VoidEventChannelSO _lobbyJoinedEvent; 48 [SerializeField] 49 private IntEventChannelSO _changePlayerColorId; 50 [SerializeField] 51 private VoidEventChannelSO _leaveGameToMainMenuEvent; 52 [SerializeField] 53 private ULongEventChannelSO _kickPlayerEvent; 54 [SerializeField] 55 private StringEventChannelSO _setPlayerNameEvent; 56 [SerializeField] 57 private TryToSpawnRoomObjectChannelSO _tryToSpawnRoomObjectEvent; 58 59 [Header("Invoking Func")] 60 [SerializeField] 61 private StringFuncSO _getCurrentSceneNameFunc; 62 63 [Header("Setting Func")] 64 [SerializeField] 65 private IntBoolFuncSO _isPlayerIndexConnected; 66 [SerializeField] 67 private IntPlayerdataFuncSO _getPlayerDataFromPlayerIndex; 68 [SerializeField]
B.6. FixingGameMultiplayer NOT FINAL VERSION 63 69 private IntColorFuncSO _getPlayerColorFunc; 70 [SerializeField] 71 private PlayerdataFuncSO _getClientPlayerData; 72 [SerializeField] 73 private StringFuncSO _getPlayerNameFunc; 74 //[SerializeField] 75 //private SpawnRoomObjectFuncSO _spawnRoomObjectFunc; 76 77 private void Awake() 78 { 79 if (Instance != null && Instance != this) 80 { 81 Destroy(this); 82 } 83 else 84 { 85 Instance = this; 86 DontDestroyOnLoad(gameObject); 87 } 88 // si sobra tiempo, refactorizar a un FuncSO y que el sistema de guardado sea externo 89 _playerName = PlayerPrefs.GetString(PLAYER_PREFS_PLAYER_NAME_MULTIPLAYER, $"PlayerName{Random.Range(100, 1000)}"); 90 91 _playerDataNetworkList = new NetworkList<PlayerData>(readPerm: NetworkVariableReadPermission.Everyone); 92 _playerDataNetworkList.OnListChanged += OnPlayerDataNetworkListChanged; 93 94 // clear funcs just in case 95 _isPlayerIndexConnected.ClearOnFuncRaised(); 96 _getPlayerDataFromPlayerIndex.ClearOnFuncRaised(); 97 _getPlayerColorFunc.ClearOnFuncRaised(); 98 _getClientPlayerData.ClearOnFuncRaised(); 99 _getPlayerNameFunc.ClearOnFuncRaised(); 100 //_spawnRoomObjectFunc.ClearOnFuncRaised(); 101 102 // set funcs 103 _isPlayerIndexConnected.TrySetOnFuncRaised(IsPlayerIndexConnected); 104 _getPlayerDataFromPlayerIndex.TrySetOnFuncRaised(GetPlayerDataFromPlayerIndex); 105 _getPlayerColorFunc.TrySetOnFuncRaised(GetPlayerColor); 106 _getClientPlayerData.TrySetOnFuncRaised(GetPlayerData); 107 _getPlayerNameFunc.TrySetOnFuncRaised(GetPlayerName); 108 //_spawnRoomObjectFunc.TrySetOnFuncRaised(SpawnRoomObject); 109 } 110 111 private void OnEnable() 112 { 113 _lobbyCreatedEvent.OnEventRaised += StartHost; 114 _lobbyJoinedEvent.OnEventRaised += StartClient; 115 116 _changePlayerColorId.OnEventRaised += ChangePlayerColor; 117 118 _leaveGameToMainMenuEvent.OnEventRaised += LeaveToMainMenu; 119
70 Source code 7using Unity.Netcode.Transports.UTP; 8using Unity.Networking.Transport.Relay; 9using Unity.Services.Authentication; 10 using Unity.Services.Core; 11 using Unity.Services.Lobbies; 12 using Unity.Services.Lobbies.Models; 13 using Unity.Services.Relay; 14 using Unity.Services.Relay.Models; 15 using UnityEngine; 16 17 namespace FixingIt.GameLobby 18 { 19 // It is a Singleton just to work through scenes and delete it whenever I want 20 public class LobbyManager : MonoBehaviour 21 { 22 private const int MAX_PLAYER_AMOUNT = 4; 23 private const string DTLS_CONNECTION_TYPE = "dtls"; //type that Unity docummentation recommends 24 private const string RELAY_JOIN_CODE = "RelayJoinCode"; 25 26 private const string CREATE_LOBBY_MSG = "Creating lobby..."; 27 private const string CREATE_RELAY_MSG = "Creating relay..."; 28 private const string JOIN_LOBBY_MSG = "Joining lobby..."; 29 private const string JOIN_RELAY_MSG = "Joining relay..."; 30 private const string SEARCHING_LOBBIES_MSG = "Searching for public lobbies..."; 31 32 public static LobbyManager Instance { get; private set;} 33 34 private const string PLAYER_NAME = "PlayerName"; 35 36 private Lobby _hostLobby; 37 private Lobby _joinedLobby; 38 private float _heartbeatTimer; 39 private float _lobbyUpdateTimer; 40 private string _playerName; 41 42 [Header("Broadcasting To")] 43 [SerializeField] 44 private LobbiesChannelSO _lobbiesListedEvent; 45 [SerializeField] 46 private VoidEventChannelSO _lobbyCreatedEvent; 47 [SerializeField] 48 private VoidEventChannelSO _lobbyJoinedEvent; 49 [SerializeField] 50 private StringEventChannelSO _lobbyErrorCatchedEvent; 51 [SerializeField] 52 private StringEventChannelSO _lobbyStateUpdated; 53 54 [Header("Listening To")] 55 [SerializeField] 56 private VoidEventChannelSO _refreshLobbiesListEvent; 57 [SerializeField]
B.7. LobbyManager 71 58 private CreateLobbyChannelSO _createLobbyChannel; 59 [SerializeField] 60 private StringEventChannelSO _joinByIdEvent; 61 [SerializeField] 62 private StringEventChannelSO _joinByCodeEvent; 63 [SerializeField] 64 private VoidEventChannelSO _allPlayersReadyEvent; 65 [SerializeField] 66 private VoidEventChannelSO _toMainMenuScreenEvent; 67 [SerializeField] 68 private VoidEventChannelSO _leaveGameToMainMenuEvent; 69 [SerializeField] 70 private StringEventChannelSO _kickPlayerPlayerIdEvent; 71 [SerializeField] 72 private StringEventChannelSO _playerIdDisconnectedEvent; 73 74 [Header("Setting Func")] 75 [SerializeField] 76 private StringFuncSO _getLobbyNameFunc; 77 [SerializeField] 78 private StringFuncSO _getLobbyCodeFunc; 79 80 private void Awake() 81 { 82 if (Instance != null && Instance != this) { 83 Destroy(this); 84 } 85 else { 86 Instance = this; 87 DontDestroyOnLoad(gameObject); 88 } 89 90 // clear funcs just in case 91 _getLobbyNameFunc.ClearOnFuncRaised(); 92 _getLobbyCodeFunc.ClearOnFuncRaised(); 93 94 // set funcs 95 _getLobbyNameFunc.TrySetOnFuncRaised(() => _joinedLobby.Name); 96 _getLobbyCodeFunc.TrySetOnFuncRaised(() => _joinedLobby.LobbyCode); 97 } 98 99 private void OnEnable() 100 { 101 _refreshLobbiesListEvent.OnEventRaised += ListLobbies; 102 _createLobbyChannel.OnEventRaised += CreateLobby; 103 _joinByIdEvent.OnEventRaised += JoinLobbyById; 104 _joinByCodeEvent.OnEventRaised += JoinLobbyByCode; 105 106 _allPlayersReadyEvent.OnEventRaised += DeleteLobby; 107 108 _toMainMenuScreenEvent.OnEventRaised += LeaveLobby;
72 Source code 109 _leaveGameToMainMenuEvent.OnEventRaised += LeaveLobby; 110 111 //_kickPlayerPlayerIdEvent.OnEventRaised += KickPlayer; 112 _playerIdDisconnectedEvent.OnEventRaised += KickPlayer; 113 } 114 115 private void OnDisable() 116 { 117 _refreshLobbiesListEvent.OnEventRaised -= ListLobbies; 118 _createLobbyChannel.OnEventRaised -= CreateLobby; 119 _joinByIdEvent.OnEventRaised -= JoinLobbyById; 120 _joinByCodeEvent.OnEventRaised -= JoinLobbyByCode; 121 122 _allPlayersReadyEvent.OnEventRaised -= DeleteLobby; 123 124 _toMainMenuScreenEvent.OnEventRaised -= LeaveLobby; 125 _leaveGameToMainMenuEvent.OnEventRaised -= LeaveLobby; 126 127 //_kickPlayerPlayerIdEvent.OnEventRaised -= KickPlayer; 128 _playerIdDisconnectedEvent.OnEventRaised -= KickPlayer; 129 } 130 131 private async void Start() 132 { 133 // to prevent initialize and signin when we are signed 134 if (UnityServices.State != ServicesInitializationState.Initialized) 135 { 136 InitializationOptions initializationOptions = new InitializationOptions(); 137 initializationOptions.SetProfile(Random.Range(0, 1000).ToString()); // to allow test with multiple builds 138 139 await UnityServices.InitializeAsync(initializationOptions); 140 141 await AuthenticationService.Instance.SignInAnonymouslyAsync(); 142 } 143 144 _playerName = $"Guest{Random.Range(1000, 9999)}"; // It is not unique 145 Debug.Log(_playerName); 146 147 ListLobbies(); 148 } 149 150 private void Update() 151 { 152 HandleLobbyHeartBeat(); 153 //HandleLobbyPollForUpdates(); 154 } 155 156 #region HandleLobby 157 private async void HandleLobbyHeartBeat() 158 { 159 if (!IsLobbyHost())
B.7. LobbyManager 73 160 return; 161 162 _heartbeatTimer -= Time.deltaTime; 163 if (_heartbeatTimer < 0f) 164 { 165 float heartbeatTimerMax = 15f; 166 _heartbeatTimer = heartbeatTimerMax; 167 168 await LobbyService.Instance.SendHeartbeatPingAsync(_joinedLobby.Id); 169 } 170 } 171 172 private async void HandleLobbyPollForUpdates() 173 { 174 if (!IsLobbyHost()) 175 return; 176 177 _lobbyUpdateTimer -= Time.deltaTime; 178 if (_lobbyUpdateTimer < 0f) 179 { 180 float lobbyUpdateTimerMax = 1.1f; 181 _lobbyUpdateTimer = lobbyUpdateTimerMax; 182 183 Lobby lobby = await LobbyService.Instance.GetLobbyAsync(_joinedLobby.Id); 184 _joinedLobby = lobby; 185 186 // TODO: send event to Update UI 187 } 188 } 189 #endregion 190 191 private bool IsLobbyHost() 192 { 193 return _joinedLobby != null 194 && _joinedLobby.HostId == AuthenticationService.Instance.PlayerId; 195 } 196 197 private async void ListLobbies() 198 { 199 try 200 { 201 _lobbyStateUpdated.RaiseEvent(SEARCHING_LOBBIES_MSG); 202 203 // lobbies with al least 1 slot and sorted in created order 204 QueryLobbiesOptions queryLobbiesOptions = new QueryLobbiesOptions 205 { 206 Filters = new List<QueryFilter> { 207 new QueryFilter(QueryFilter.FieldOptions.AvailableSlots, "0", QueryFilter.OpOptions.GT) // con al menos 1 hueco 208 // I can put another filter to compare the data, for example for the GameMode, not necessary in my game 209 //new QueryFilter(QueryFilter.FieldOptions.S1, "SpeedFix", QueryFilter.OpOptions.EQ) 210 },
74 Source code 211 Order = new List<QueryOrder> { 212 new QueryOrder (false, QueryOrder.FieldOptions.Created) 213 } 214 }; 215 216 QueryResponse queryResponse = await Lobbies.Instance.QueryLobbiesAsync(queryLobbiesOptions); 217 218 // send event 219 _lobbiesListedEvent.RaiseEvent(queryResponse.Results); 220 } 221 catch (LobbyServiceException e) 222 { 223 ManageLobbyErrors(e); 224 } 225 } 226 227 #region Relay 228 private async Task<Allocation> AllocateRelay() 229 { 230 try { 231 // max players - the host 232 Allocation allocation = await RelayService.Instance.CreateAllocationAsync(MAX_PLAYER_AMOUNT - 1); 233 234 return allocation; 235 } 236 catch (RelayServiceException e) { 237 ManageRelayErrors(e); 238 239 return default; 240 } 241 } 242 243 private async Task<string> GetRelayJoinCode(Allocation allocation) 244 { 245 try { 246 247 string relayJoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId); 248 249 return relayJoinCode; 250 } 251 catch(RelayServiceException e) { 252 ManageRelayErrors(e); 253 254 return default; 255 } 256 } 257 258 private async Task<JoinAllocation> JoinRelay(string joinCode) 259 { 260 try { 261 JoinAllocation joinAllocation = await RelayService.Instance.JoinAllocationAsync(joinCode);
B.7. LobbyManager 75 262 263 return joinAllocation; 264 } 265 catch (RelayServiceException e) { 266 ManageRelayErrors(e); 267 268 return default; 269 } 270 } 271 272 private async Task JoinRelayTransport(Lobby lobbyJoined) 273 { 274 string relayJoinCode = lobbyJoined.Data[RELAY_JOIN_CODE].Value; 275 JoinAllocation joinAllocation = await JoinRelay(relayJoinCode); 276 277 NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new RelayServerData(joinAllocation, DTLS_CONNECTION_TYPE)); 278 } 279 #endregion 280 281 private async void CreateLobby(string lobbyName, bool isPrivate) 282 { 283 try 284 { 285 _lobbyStateUpdated.RaiseEvent(CREATE_LOBBY_MSG); 286 287 CreateLobbyOptions createLobbyOptions = new CreateLobbyOptions 288 { 289 IsPrivate = isPrivate, 290 Player = GetPlayer(), 291 }; 292 293 Lobby lobby = await LobbyService.Instance.CreateLobbyAsync(lobbyName, MAX_PLAYER_AMOUNT, createLobbyOptions); 294 295 _hostLobby = lobby; 296 _joinedLobby = _hostLobby; 297 298 Debug.Log($"Created lobby! {lobby.Name}, {lobby.MaxPlayers}, {lobby.Id}, {lobby.LobbyCode}"); 299 300 // create relay 301 _lobbyStateUpdated.RaiseEvent(CREATE_RELAY_MSG); 302 303 Allocation allocation = await AllocateRelay(); 304 305 string relayJoinCode = await GetRelayJoinCode(allocation); 306 307 await LobbyService.Instance.UpdateLobbyAsync(_joinedLobby.Id, new UpdateLobbyOptions { 308 Data = new Dictionary<string, DataObject> { 309 {RELAY_JOIN_CODE, new DataObject(DataObject.VisibilityOptions.Member, relayJoinCode)} 310 } 311 }); 312
76 Source code 313 NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new RelayServerData(allocation, DTLS_CONNECTION_TYPE)); 314 315 // send event 316 _lobbyCreatedEvent.RaiseEvent(); 317 } 318 catch (LobbyServiceException e) 319 { 320 ManageLobbyErrors(e); 321 } 322 } 323 324 private async void JoinLobbyById(string lobbyId) 325 { 326 try 327 { 328 _lobbyStateUpdated.RaiseEvent(JOIN_LOBBY_MSG); 329 330 JoinLobbyByIdOptions joinLobbyByIdOptions = new JoinLobbyByIdOptions 331 { 332 Player = GetPlayer() 333 }; 334 335 Lobby lobby = await Lobbies.Instance.JoinLobbyByIdAsync(lobbyId, joinLobbyByIdOptions); 336 _joinedLobby = lobby; 337 338 Debug.Log($"Joined Lobby with id: {lobbyId}"); 339 340 // join relay 341 _lobbyStateUpdated.RaiseEvent(JOIN_RELAY_MSG); 342 343 await JoinRelayTransport(_joinedLobby); 344 345 // send event 346 _lobbyJoinedEvent.RaiseEvent(); 347 } 348 catch (LobbyServiceException e) 349 { 350 ManageLobbyErrors(e); 351 } 352 } 353 354 private async void JoinLobbyByCode(string lobbyCode) 355 { 356 try 357 { 358 _lobbyStateUpdated.RaiseEvent(JOIN_LOBBY_MSG); 359 360 JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions 361 { 362 Player = GetPlayer() 363 };
B.7. LobbyManager 77 364 365 Lobby lobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions); 366 _joinedLobby = lobby; 367 368 // join relay 369 _lobbyStateUpdated.RaiseEvent(JOIN_RELAY_MSG); 370 371 await JoinRelayTransport(_joinedLobby); 372 373 // send event 374 _lobbyJoinedEvent.RaiseEvent(); 375 } 376 catch (LobbyServiceException e) 377 { 378 ManageLobbyErrors(e); 379 } 380 } 381 382 private async void DeleteLobby() 383 { 384 if (!IsLobbyHost()) 385 return; 386 387 try { 388 await LobbyService.Instance.DeleteLobbyAsync(_joinedLobby.Id); 389 390 _joinedLobby = null; 391 } 392 catch (LobbyServiceException e) { 393 ManageLobbyErrors(e); 394 } 395 } 396 397 private async void LeaveLobby() 398 { 399 if (_joinedLobby == null) 400 return; 401 402 try { 403 //if (IsLobbyHost()) { 404 // DeleteLobby(); 405 //} 406 407 await LobbyService.Instance.RemovePlayerAsync(_joinedLobby.Id, AuthenticationService.Instance.PlayerId); 408 409 _joinedLobby = null; 410 } 411 catch (LobbyServiceException e) { 412 ManageLobbyErrors(e); 413 } 414 }
78 Source code 415 416 // When player kicked, managed by the FixingGameMultiplayer, NetworkManager 417 private async void KickPlayer(string playerId) 418 { 419 if (!IsLobbyHost()) 420 return; 421 422 try { 423 await LobbyService.Instance.RemovePlayerAsync(_joinedLobby.Id, playerId); 424 } 425 catch (LobbyServiceException e) { 426 ManageLobbyErrors(e); 427 } 428 } 429 430 #region PlayerLobby 431 private Player GetPlayer() 432 { 433 return new Player 434 { 435 Data = new Dictionary<string, PlayerDataObject> { 436 {PLAYER_NAME, new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member, _playerName) } 437 } 438 }; 439 } 440 #endregion 441 442 private void ManageLobbyErrors(LobbyServiceException e) 443 { 444 Debug.LogException(e); 445 446 string userErrorMsg = e.Message; 447 userErrorMsg = userErrorMsg[0].ToString().ToUpper() + userErrorMsg.Substring(1); 448 449 _lobbyErrorCatchedEvent.RaiseEvent(userErrorMsg); 450 } 451 452 private void ManageRelayErrors(RelayServiceException e) 453 { 454 Debug.LogException(e); 455 456 string userErrorMsg = e.Message; 457 userErrorMsg = userErrorMsg[0].ToString().ToUpper() + userErrorMsg.Substring(1); 458 459 _lobbyErrorCatchedEvent.RaiseEvent(userErrorMsg); 460 } 461 } 462 }
B.8. CharacterSelectionPlayer 79 B.8 CharacterSelectionPlayer 1using FixingIt.Funcs; 2using FixingIt.PlayerGame; 3using ProgramadorCastellano.Events; 4using ProgramadorCastellano.Funcs; 5using TMPro; 6using Unity.Netcode; 7using UnityEngine; 8using UnityEngine.UI; 9 10 namespace FixingIt.CharacterSelection 11 { 12 public class CharacterSelectionPlayer : MonoBehaviour 13 { 14 [SerializeField] private int _playerIndex; 15 [SerializeField] private GameObject _readyGameObject; 16 [SerializeField] private TextMeshPro _playerNameText; 17 [SerializeField] private PlayerVisualComp _playerVisualComp; 18 [SerializeField] private Button _kickButton; 19 20 [Header("Broadcasting To")] 21 [SerializeField] 22 private ULongEventChannelSO _kickPlayerClientIdEvent; 23 [SerializeField] 24 private StringEventChannelSO _kickPlayerPlayerIdEvent; 25 26 [Header("Listening To")] 27 [SerializeField] 28 private VoidEventChannelSO _playerDataNetworkListChangedEvent; 29 [SerializeField] 30 private VoidEventChannelSO _clientReadyChangedEvent; 31 32 [Header("Invoking Func")] 33 [SerializeField] 34 private IntBoolFuncSO _isPlayerIndexConnectedFunc; 35 [SerializeField] 36 private ULongBoolFuncSO _isPlayerReadyFunc; 37 [SerializeField] 38 private IntPlayerdataFuncSO _getPlayerDataFromPlayerIndexFunc; 39 [SerializeField] 40 private IntColorFuncSO _getPlayerColorFunc; 41 [SerializeField] 42 private StringFuncSO _getPlayerNameFunc; 43 44 private void Awake() 45 { 46 _kickButton.onClick.AddListener(KickPlayer); 47 } 48
86 Source code 86 } 87 88 private void OnEnable() 89 { 90 _inMenuEvent.OnEventRaised += ToMenuMode; 91 _outMenuEvent.OnEventRaised += ToGameplayMode; 92 93 _customerWithObjectFixedEvent.OnEventRaised += ObjectFixedAndReturned; 94 } 95 96 private void OnDisable() 97 { 98 _inMenuEvent.OnEventRaised -= ToMenuMode; 99 _outMenuEvent.OnEventRaised -= ToGameplayMode; 100 101 _customerWithObjectFixedEvent.OnEventRaised += ObjectFixedAndReturned; 102 } 103 104 private void Start() 105 { 106 //_gameState = GameState.WaitingToStart; 107 _inputReaderSO.DisableAllInput(); 108 } 109 110 public override void OnNetworkSpawn() 111 { 112 _gameState.OnValueChanged += State_OnValueChanged; 113 114 if (IsServer) { 115 NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += NM_SM_OnLoadEventCompleted; 116 } 117 } 118 119 private void State_OnValueChanged(GameState previousValue, GameState newValue) 120 { 121 switch (newValue) 122 { 123 case GameState.WaitingToStart: 124 _inputReaderSO.DisableAllInput(); 125 break; 126 case GameState.Playing: 127 _inputReaderSO.EnableGameplayInput(); 128 break; 129 case GameState.End: 130 _inputReaderSO.EnableMenuInput(); 131 _numberObjectsFixedEvent.RaiseEvent(_numberObjectsFixed.Value); 132 break; 133 default: 134 break; 135 } 136 }
B.10. FixingGameManager 87 137 138 private void NM_SM_OnLoadEventCompleted(string sceneName, LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut) 139 { 140 for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsIds.Count; i++) { 141 ulong clientId = NetworkManager.Singleton.ConnectedClientsIds[i]; 142 143 GameObject playerGO = Instantiate(_playerPrefab, _baseTransformToSpawn); 144 playerGO.transform.position = _playerSpawnPositions[i].position; 145 playerGO.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true); 146 Debug.Log(playerGO.GetComponent<NetworkObject>().OwnerClientId); 147 Debug.Log(NetworkManager.Singleton.LocalClientId); 148 } 149 } 150 151 private void Update() 152 { 153 if (!IsServer) { 154 return; 155 } 156 157 switch (_gameState.Value) { 158 case GameState.WaitingToStart: 159 // esperar countdown to start 160 _waitingToStartTimer -= Time.deltaTime; 161 if (_waitingToStartTimer < 0f) { 162 _gameState.Value = GameState.Playing; 163 //_inputReaderSO.EnableGameplayInput(); 164 } 165 166 WaitingToStartRaiseEventClientRpc(_waitingToStartTimer); 167 //_waitingToStartTimerEvent.RaiseEvent(_waitingToStartTimer); 168 break; 169 case GameState.Playing: 170 // timer juego 171 _gameplayTimer -= Time.deltaTime; 172 if (_gameplayTimer < 0f) { 173 _gameState.Value = GameState.End; 174 //_inputReaderSO.EnableMenuInput(); 175 176 //_numberObjectsFixedEvent.RaiseEvent(_numberObjectsFixed); 177 } 178 179 // timer npcs 180 _customerSpawnerTimer -= Time.deltaTime; 181 if (_customerSpawnerTimer < 0f) { 182 _customerSpawnerTimer = _customerSpawnerTimerMax; 183 184 SpawnNewCustomer(); 185 } 186 187 float gameplayTimerNormalized = GetTimerNormalized(_gameplayTimer, _gameplayTimerMax);
88 Source code 188 GameplayTimerNormalizedRaiseEventClientRpc(gameplayTimerNormalized); 189 //_gameplayTimerNormalizedEvent.RaiseEvent(GetTimerNormalized(_gameplayTimer, _gameplayTimerMax)); 190 break; 191 case GameState.End: 192 // mostrar puntuacion 193 Debug.Log(_numberObjectsFixed); 194 break; 195 default: 196 Debug.LogWarning($"{_gameState} is not implemented"); 197 break; 198 } 199 200 201 } 202 203 [ClientRpc] 204 private void WaitingToStartRaiseEventClientRpc(float waitingToStartTimer) 205 { 206 _waitingToStartTimerEvent.RaiseEvent(waitingToStartTimer); 207 } 208 209 [ClientRpc] 210 private void GameplayTimerNormalizedRaiseEventClientRpc(float gameplayTimerNormalized) 211 { 212 _gameplayTimerNormalizedEvent.RaiseEvent(gameplayTimerNormalized); 213 } 214 215 private float GetTimerNormalized(float timer, float timerMax) 216 { 217 return timer / timerMax; 218 } 219 220 #region GameplayMode 221 private void ToMenuMode() 222 { 223 _inputReaderSO.EnableMenuInput(); 224 } 225 226 private void ToGameplayMode() 227 { 228 _inputReaderSO.EnableGameplayInput(); 229 } 230 #endregion 231 232 #region Game Loop 233 234 #region CustomerCounters 235 private CustomerCounter GetFirstCustomerCounterFree() 236 { 237 foreach (CustomerCounter counter in _customerCounters) { 238 if (!counter.HasCustomerAssigned()) {
B.10. FixingGameManager 89 239 return counter; 240 } 241 } 242 243 return null; 244 } 245 246 private int GetCustomerCounterIndex(CustomerCounter customerCounter) 247 { 248 return System.Array.IndexOf(_customerCounters, customerCounter); 249 } 250 251 private CustomerCounter GetCustomerCounterFromIndex(int index) 252 { 253 return _customerCounters[index]; 254 } 255 #endregion 256 257 #region ObjectToFixSO 258 private RoomObjectSO GetRandomObjecToFixSO() 259 { 260 int randIndex = Random.Range(0, _objectsToFixSO.Length); 261 262 return _objectsToFixSO[randIndex]; 263 } 264 265 private int GetObjectToFixSOIndex(RoomObjectSO roomObjectSO) 266 { 267 return System.Array.IndexOf(_objectsToFixSO, roomObjectSO); 268 } 269 270 private RoomObjectSO GetObjectToFixSOFromIndex(int index) 271 { 272 return _objectsToFixSO[index]; 273 } 274 #endregion 275 276 private void SpawnNewCustomer() 277 { 278 CustomerCounter freeCounter = GetFirstCustomerCounterFree(); 279 if (freeCounter == null) { 280 return; 281 } 282 int freeCounterIndex = GetCustomerCounterIndex(freeCounter); 283 284 RoomObjectSO objectToFixSO = GetRandomObjecToFixSO(); 285 int objectToFixSOIndex = GetObjectToFixSOIndex(objectToFixSO); 286 287 SpawnNewCustomerServerRpc(freeCounterIndex, objectToFixSOIndex); 288 } 289
90 Source code 290 [ServerRpc] 291 private void SpawnNewCustomerServerRpc(int freeCounterIndex, int objectToFixSOIndex) 292 { 293 GameObject customerGO = Instantiate(_customerPrefab, _customerStartPosition.position, Quaternion.identity); 294 customerGO.transform.position = _customerStartPosition.position; 295 customerGO.transform.rotation = _customerStartPosition.rotation; 296 297 298 CustomerController customerController = customerGO.GetComponent<CustomerController>(); 299 300 if (customerController == null) { 301 Debug.LogError($"The prefab {_customerPrefab} is not a Customer Controller"); 302 return; 303 } 304 305 NetworkObject customerNO = customerGO.GetComponent<NetworkObject>(); 306 customerNO.Spawn(); 307 customerGO.transform.parent = RoomObject.StaticInSceneTransform; 308 309 CustomerCounter freeCounter = GetCustomerCounterFromIndex(freeCounterIndex); 310 RoomObjectSO objectToFixSO = GetObjectToFixSOFromIndex(objectToFixSOIndex); 311 customerController.InitCustomer(_customerStartPosition, freeCounter, objectToFixSO); 312 freeCounter.SetCustomerAssigned(customerController); 313 314 315 RoomObject.SpawnRoomObject(objectToFixSO, customerController); 316 } 317 318 private void ObjectFixedAndReturned(IRoomObjectParent customerWithObject) 319 { 320 _numberObjectsFixed.Value++; 321 } 322 #endregion 323 } 324 } B.11 RoomObject NOT FINAL VERSION 1using FixingIt.ActorComponents; 2using FixingIt.Events; 3using FixingIt.RoomObjects.SO; 4using ProgramadorCastellano.Events; 5using Unity.Netcode; 6using UnityEngine; 7 8namespace FixingIt.RoomObjects.Logic 9{ 10 [RequireComponent(typeof(FollowTransformComponent))]
B.11. RoomObject NOT FINAL VERSION 91 11 public class RoomObject : NetworkBehaviour 12 { 13 private static TryToSpawnRoomObjectChannelSO _staticTryToSpawnRoomObjectEvent; 14 public static Transform StaticInSceneTransform { get; private set; } 15 16 [SerializeField] private RoomObjectSO _roomObjectSO; 17 [SerializeField] private int _numberOfUses = 1; 18 19 [Header("Components")] 20 [SerializeField] private AudioComponent _roomObjectUsedAudioComp; 21 [SerializeField] private AudioComponent _roomObjectBrokenAudioComp; 22 private FollowTransformComponent _followTransformComp; 23 24 [Header("Broadcasting To")] 25 //[SerializeField] 26 //private VoidEventChannelSO _roomObjectUsedEvent; 27 [SerializeField] 28 private VoidEventChannelSO _roomObjectBrokenAfterUseEvent; 29 [SerializeField] 30 private TryToSpawnRoomObjectChannelSO _tryToSpawnRoomObjectEvent; // its value should be the same among all the roomObjects 31 32 private IRoomObjectParent _roomObjectParent; 33 34 public RoomObjectSO RoomObjectSO => _roomObjectSO; 35 public GameObject RoomObjectVisualPrefab => transform.GetChild(0).gameObject; 36 37 protected virtual void Awake() 38 { 39 _followTransformComp = GetComponent<FollowTransformComponent>(); 40 } 41 42 private void Start() 43 { 44 if (_tryToSpawnRoomObjectEvent != null) { 45 _staticTryToSpawnRoomObjectEvent = _tryToSpawnRoomObjectEvent; 46 StaticInSceneTransform = transform; 47 } 48 } 49 50 public void SetRoomObjectParent(IRoomObjectParent newRoomObjectParent) 51 { 52 SetRoomObjectParentServerRpc(newRoomObjectParent.GetNetworkObject()); 53 } 54 55 [ServerRpc(RequireOwnership = false)] 56 private void SetRoomObjectParentServerRpc(NetworkObjectReference newRoomObjectParentNORef) 57 { 58 transform.parent = StaticInSceneTransform; 59 SetRoomObjectParentClientRpc(newRoomObjectParentNORef); 60 } 61
92 Source code 62 [ClientRpc] 63 private void SetRoomObjectParentClientRpc(NetworkObjectReference newRoomObjectParentNORef) 64 { 65 newRoomObjectParentNORef.TryGet(out NetworkObject newRoomObjectParentNO); 66 IRoomObjectParent newRoomObjectParent = newRoomObjectParentNO.GetComponent<IRoomObjectParent>(); 67 68 // clear parent info 69 _roomObjectParent?.ClearRoomObject(); 70 71 // set new parent 72 _roomObjectParent = newRoomObjectParent; 73 74 if (newRoomObjectParent.HasRoomObject()) 75 { 76 Debug.LogError("IRoomObjectParent already has a RoomObject"); 77 } 78 79 newRoomObjectParent.SetRoomObject(this); 80 81 // set transform 82 _followTransformComp.SetTargetTransform(newRoomObjectParent.GetRoomObjectTransform()); 83 } 84 85 public void Use() 86 { 87 _numberOfUses--; 88 89 if (_numberOfUses <= 0) 90 { 91 _roomObjectBrokenAfterUseEvent.RaiseEvent(); 92 93 //if (_roomObjectBrokenAudioComp == null) { 94 // Debug.LogWarning("Only Tools should be broken"); 95 //} 96 //else { 97 // _roomObjectBrokenAudioComp.PlaySound(); 98 //} 99 Broke(); 100 } 101 else 102 { 103 if (_roomObjectUsedAudioComp == null) 104 { 105 Debug.LogWarning("Only Tools should be used"); 106 } 107 else 108 { 109 _roomObjectUsedAudioComp.PlaySound(false); 110 } 111 } 112 }
B.12. IRoomObjectParent 93 113 114 // TODO: cambiar por sistema de pooling como extra 115 public void Broke() 116 { 117 _roomObjectParent.ClearRoomObject(); 118 119 Destroy(gameObject); 120 } 121 122 #region Static 123 // TODO: cambiar por sistema de pooling como extra 124 public static void SpawnRoomObject(RoomObjectSO roomObjectSO, IRoomObjectParent roomObjectParent) 125 { 126 _staticTryToSpawnRoomObjectEvent.RaiseEvent(roomObjectSO, roomObjectParent.GetNetworkObject()); 127 } 128 #endregion 129 } 130 } B.12 IRoomObjectParent 1using Unity.Netcode; 2using UnityEngine; 3 4namespace FixingIt.RoomObjects.Logic 5{ 6public interface IRoomObjectParent 7{ 8public Transform transform { get; } 9 10 public Transform GetRoomObjectTransform(); 11 public RoomObject GetRoomObject(); 12 public void SetRoomObject(RoomObject roomObject); 13 public bool HasRoomObject(); 14 public void ClearRoomObject(); 15 16 public NetworkObject GetNetworkObject(); 17 } 18 } B.13 ToFixRoomObject 1using FixingIt.RoomObjects.SO; 2using System.Linq; 3using UnityEngine; 4
94 Source code 5namespace FixingIt.RoomObjects.Logic 6{ 7public class ToFixRoomObject : RoomObject 8{ 9[SerializeField] private ToFixRoomObjectVisualComp _toFixRoomObjectVisualComp; 10 [SerializeField] private RoomObjectSO[] _toolsToBeFixedSO; 11 private bool[] _toolsUsedSO; 12 13 public bool IsFixed => _toolsUsedSO.All(valor => valor); 14 15 protected override void Awake() 16 { 17 base.Awake(); 18 _toolsUsedSO = new bool[_toolsToBeFixedSO.Length]; 19 } 20 21 private void Start() 22 { 23 _toFixRoomObjectVisualComp.UpdateTFROVisual(_toolsToBeFixedSO, _toolsUsedSO); 24 } 25 26 //private void FixObject() 27 //{ 28 // // change visual? 29 // _toFixRoomObjectVisualComp.UpdateTFROVisual(_toolsToBeFixedSO, _toolsUsedSO); 30 // Debug.Log("FixObject"); 31 //} 32 33 public bool TryToFix(RoomObjectSO toolUsed, out bool toolBeenUsed) 34 { 35 toolBeenUsed = false; 36 37 // should be check from outside but just in case 38 if (IsFixed) 39 { 40 Debug.Log("cannot fix a object that is already fixed"); 41 return false; 42 } 43 44 for (int i=0;i<_toolsToBeFixedSO.Length; i++) 45 { 46 if (_toolsUsedSO[i]) 47 continue; 48 49 if (toolUsed == _toolsToBeFixedSO[i]) 50 { 51 _toolsUsedSO[i] = true; 52 toolBeenUsed = true; 53 break; 54 } 55 }
B.14. PlayerController 95 56 57 _toFixRoomObjectVisualComp.UpdateTFROVisual(_toolsToBeFixedSO, _toolsUsedSO); 58 59 if (!IsFixed) 60 return false; 61 62 return true; 63 } 64 } 65 } B.14 PlayerController 1using FixingIt.ActorComponents; 2using FixingIt.Counters; 3using FixingIt.InputSystem; 4using FixingIt.RoomObjects.Logic; 5using ProgramadorCastellano.Funcs; 6using Unity.Netcode; 7using UnityEngine; 8 9namespace FixingIt.PlayerGame 10 { 11 [RequireComponent(typeof(Rigidbody))] 12 public class PlayerController : NetworkBehaviour, IRoomObjectParent 13 { 14 [SerializeField] InputReaderSO _inputReaderSO; 15 16 [SerializeField] private Transform _holdingPoint; 17 18 [Header("Player Comps")] 19 [SerializeField] private PlayerVisualComp _playerVisualComp; 20 [SerializeField] private PlayerAnimationComp _animationComp; 21 [SerializeField] private AudioComponent _audioComp; 22 23 [Header("Player Stats")] 24 [SerializeField] private float _moveSpeed = 5f; 25 [SerializeField] private float _rotateSpeed = 10f; 26 [SerializeField] private float _interactDistance = 2f; 27 [SerializeField] private LayerMask _countersLayerMask; 28 29 [Header("Invoking Func")] 30 [SerializeField] 31 private ULongColorFuncSO _getColorFromClientIdFunc; 32 33 private Rigidbody _rb; 34 private RoomObject _roomObject; 35 private Vector2 _direction;
102 Source code 40 41 private void Start() 42 { 43 if (!IsServer) 44 return; 45 46 GoToCounter(); 47 } 48 49 private void Update() 50 { 51 if (!IsServer) 52 return; 53 54 switch (_clientState) 55 { 56 case ClientState.Waiting: 57 break; 58 case ClientState.GoingToCounter: 59 _audioComp.PlaySound(); 60 if (_agent.remainingDistance < _agent.stoppingDistance) 61 { 62 _clientState = ClientState.Waiting; 63 _roomObject.SetRoomObjectParent(_parentToLeaveBrokenObject); 64 65 _audioComp.StopSound(); 66 } 67 break; 68 case ClientState.LeavingCounter: 69 _audioComp.PlaySound(); 70 if (_agent.remainingDistance < _agent.stoppingDistance) 71 { 72 // si da tiempo cambiarlo por un sistema de pooling 73 Destroy(gameObject); 74 } 75 break; 76 default: 77 Debug.LogWarning($"{_clientState} is not implemented"); 78 break; 79 } 80 } 81 82 private void GoToCounter() 83 { 84 Debug.Log(_parentToLeaveBrokenObject != null); 85 _agent.SetDestination(_parentToLeaveBrokenObject.transform.position); 86 _clientState = ClientState.GoingToCounter; 87 } 88 89 public void LeaveCounter() 90 {
B.16. CustomerController 103 91 _agent.SetDestination(_startTransform.position); 92 _clientState = ClientState.LeavingCounter; 93 } 94 95 public void InitCustomer(Transform startTransform, IRoomObjectParent parentToLeaveBrokenObject, RoomObjectSO _objectToFixSO) 96 { 97 _startTransform = startTransform; 98 _parentToLeaveBrokenObject = parentToLeaveBrokenObject; 99 100 transform.position = _startTransform.position; 101 transform.rotation = _startTransform.rotation; 102 103 //RoomObject.SpawnRoomObject(_objectToFixSO, this); 104 } 105 106 #region RoomObjectParent 107 public Transform GetRoomObjectTransform() 108 { 109 return _holdingPoint; 110 } 111 112 public RoomObject GetRoomObject() 113 { 114 return _roomObject; 115 } 116 117 public void SetRoomObject(RoomObject roomObject) 118 { 119 _roomObject = roomObject; 120 } 121 122 public bool HasRoomObject() 123 { 124 return _roomObject != null; 125 } 126 127 public void ClearRoomObject() 128 { 129 _roomObject = null; 130 } 131 132 public NetworkObject GetNetworkObject() 133 { 134 return NetworkObject; 135 } 136 #endregion 137 } 138 }
104 Source code B.17 InputReaderSO 1using UnityEngine; 2using UnityEngine.Events; 3using UnityEngine.InputSystem; 4 5namespace FixingIt.InputSystem 6{ 7//[CreateAssetMenu(fileName = "Input Reader", menuName = "Game/ Input Reader")] 8public class InputReaderSO : ScriptableObject, GameInput.IGameplayActions, GameInput.IMenuActions 9{ 10 private GameInput _gameInput; 11 12 // Assign delegate{} to events to initialise them with an empty delegate 13 // so we can skip the null check when we use them 14 15 // Gameplay 16 public event UnityAction<Vector2> MoveEvent = delegate { }; 17 public event UnityAction InteractEvent = delegate { }; 18 public event UnityAction AlternateInteractEvent = delegate { }; 19 20 // Menu 21 public event UnityAction MenuConfirmEvent = delegate { }; 22 public event UnityAction MenuCancelEvent = delegate { }; 23 public event UnityAction<Vector2> MenuNavigationEvent = delegate { }; 24 25 /* 26 *On Enable/Disable Functions 27 */ 28 #region On Enable/Disable 29 private void OnEnable() 30 { 31 if (_gameInput == null) { 32 _gameInput = new GameInput(); 33 34 // set all callbacks 35 _gameInput.Gameplay.SetCallbacks(this); 36 _gameInput.Menu.SetCallbacks(this); 37 } 38 39 // EnableGameplayInput(); // TODO: se debe manejar de forma externa 40 } 41 42 private void OnDisable() 43 { 44 DisableAllInput(); 45 } 46 #endregion 47 48 /*
B.17. InputReaderSO 105 49 *Turn On/Off Inputs 50 */ 51 #region Turn On/Off Inputs 52 public void EnableGameplayInput() 53 { 54 DisableAllInput(); 55 56 _gameInput.Gameplay.Enable(); 57 } 58 59 public void EnableMenuInput() 60 { 61 DisableAllInput(); 62 63 _gameInput.Menu.Enable(); 64 } 65 66 public void DisableAllInput() 67 { 68 _gameInput.Gameplay.Disable(); 69 _gameInput.Menu.Disable(); 70 } 71 #endregion 72 73 /* 74 *Gameplay Acions 75 */ 76 #region Gameplay Actions 77 public void OnMove(InputAction.CallbackContext context) 78 { 79 MoveEvent.Invoke(context.ReadValue<Vector2>()); 80 } 81 82 public void OnInteract(InputAction.CallbackContext context) 83 { 84 if (context.phase == InputActionPhase.Performed) { 85 InteractEvent.Invoke(); 86 } 87 } 88 89 public void OnAlternateInteract(InputAction.CallbackContext context) 90 { 91 if (context.phase == InputActionPhase.Performed) { 92 AlternateInteractEvent.Invoke(); 93 } 94 } 95 #endregion 96 97 /* 98 *Menu Actions 99 */
106 Source code 100 #region Menu Actions 101 public void OnSubmit(InputAction.CallbackContext context) 102 { 103 if (context.phase == InputActionPhase.Performed) { 104 MenuConfirmEvent.Invoke(); 105 } 106 } 107 108 public void OnCancel(InputAction.CallbackContext context) 109 { 110 if (context.phase == InputActionPhase.Performed) { 111 MenuCancelEvent.Invoke(); 112 } 113 } 114 115 public void OnNavigation(InputAction.CallbackContext context) 116 { 117 if (context.phase == InputActionPhase.Performed) { 118 MenuNavigationEvent.Invoke(context.ReadValue<Vector2>()); 119 } 120 } 121 #endregion 122 } 123 } B.18 SelectableUIData 1using UnityEngine; 2using UnityEngine.UI; 3 4namespace ProgramadorCastellano.UI 5{ 6[RequireComponent(typeof(Selectable))] 7public class SelectableUIData : MonoBehaviour 8{ 9[SerializeField] private SelectableUISkinDataSO _skinDataSO; 10 11 private Selectable _selectable; 12 13 private void Awake() 14 { 15 //_selectable = GetComponent<Selectable>(); 16 17 OnSkinUI(); 18 } 19 20 private void OnSkinUI() 21 {
B.18. SelectableUIData 107 22 _selectable = GetComponent<Selectable>(); 23 //Debug.Log(_selectable.gameObject.name); 24 25 _selectable.colors = _skinDataSO.Colors; 26 } 27 28 29 // COMMENT THE UPDATE AFTER DESGIN 30 /*private void Update() 31 { 32 if (Application.isEditor) 33 { 34 OnSkinUI(); 35 } 36 }*/ 37 } 38 }