Creating a Shop
Designing the Shop UI and Toggling it on via Player Collider
Now that we have the ability to collect diamonds from fallen enemies, it is time to spend them on useful upgrades. For this to happen we will create a shop NPC that will sell us players some useful abilities including a castle key that will help us get into the locked castle later on the map.
Preparing the Merchant NPC & Shop UI:
If you have been following with the assistances of GameDevHQ, they will be providing you with the necessary sprites for the Shop NPC. Since this is just one giant sprite there is no need to slice, just drag and drop it into the hierarchy. I am going to be placing my Merchant NPC in this bottom partition of the map.
To work with the shop UI, I decided to redraw everything within Adobe Illustrator. By drawing out the layout within Illustrator, I am able to get a complete grasp of how the final product would look like before importing it to Unity.
Then with each individual layer, I would export the files as a PNG file for Unity to read. I would be dividing the files such as NPC_frames or NPC back ground image etc, each button would be imported as an individual piece.
In Unity, create a new Canvas and then add a UI Panel as a child object. This panel is going to house all the shop UI elements. Inside this UI panel we will start importing the different UI elements as “image components”, but if they are interactable objects such as buttons aka. Buy items buttons, they would need to be created as button components.
The final touch up, is make sure that all image objects that is on top that isn’t a button or interactive object should have the “Raycast Target” checkbox unchecked. This will allow Images that are overlapping with buttons to be clickable.
Toggling the shop UI:
As mentioned above, we are going to toggle the shop UI via player collision detection. When the player gets close to the Merchant NPC we will have the shop pop up.
Before we start scripting, we will need to add a Box Collider 2D and Rigidbody 2D component to our Merchant NPC. Make sure that the “is Trigger” object is checked on and that the gravity settings on the Rigidbody is set to zero.
Create a new C# script and name this “MerchantNPC” and drag this script into the merchant NPC.
Inside this script we are going to basically delete the start and update method, and replace everything with an On Trigger Enter 2D method.
Inside this trigger method we are going to check whenever the player tagged object makes contact with the merchant NPC. Whenever it does, we will automatically turn on the Shop UI.
To gain access to the shop UI, we will need to create a handler for it. By making it a serialized object, we are able to drag in the Shop Panel into this script.
Once you save your script, back in Unity drag the shop UI panel into the Merchant script. Make sure that the shop UI panel is disable by default. Now once your player reaches the set area, it will toggle the shop UI panel to show.