Creating the UI Manager
Linking the Shop UI to the player Gem Count
Now that we have a functioning Shop UI, it is time to update the Gem Total count to the player’s total gem count in real time, in every instance the player goes to the shop.
The UI Manager script:
The UI manager is going to be the script responsible for linking every UI element together and passing along data to elements that require it. For the shop instance we want to display the current amount of gems the player has accumulated within the shop UI. To achieve this the UI manager has to pass along the the gem total from the player script to the Merchant NPC when the player makes contact. Finally the Merchant NPC is going to update the UI Manager script while stringing together all the pieces of data to display on the Shop UI. (ie. Player > Merchant > UI Manager > Shop UI).
Create a new C# script and name it UI Manager, then we are going to start by using two static variables that will create the UI Manager to function properly.
Once that is completed, we are going to create a public variable containing text elements. Since we are using “text” we first must update the UI Manager script with the UI library.
Then we are going to append the text element into a newly created public method called “Open Shop” with an attached integer variable “gems”.
With this setup, we are able to update the text element on the Shop UI with the data passed from the player script of “total gems”.
The Merchant NPC script:
As mentioned above, the wait the player is only able to pass along data of “total gem count” to the UI manager is through the contact of Player and Merchant NPC. So within the On Trigger Enter 2D method, before we open the shop UI, we can sneak in a script that allows the player to store the data of “total gem count” that can be pass along and read by the UI Manager.
Here, once the player makes contact with the Merchant NPC, with the help of UI Manager Instance, we can link the UI manager with the player public variable “total gems”.
Back in Unity, we are going to attach the UI Manager script into the Canvas object, and at the same time drag in the text element that needs to be updated.
As a test, we can walk to the shop and change the total gem variable within the Inspector to see if the text updates or not.