To buy an item, we need to spawn the object and remove the number of coins on the server. In this lesson, we will send an event to the server and remove the coins if the player has enough of them.
Send an event to the server
When a script is on the Client Context, you can use Events.BroadcastToServer to send an event that will be received by the server in order to add some logic on the server-side. For example, to avoid cheaters, you can’t add or remove Resources on the Client Context so you must send an event to the server to make this action.
In the following code, we just added one single line in our script “UIShop” to send an event called “BuyHat” to the server.
functionOnBuyHat(button)if PLAYER:GetResource("Coins") < HAT_PRICE thenprint("Not enough coins")
Create a script called ShopServer and move it in the Shop group, next to the Client Context (not inside as this would make this script in the Client Context).
When receiving an event on the server, you can use Events.Connect or Events.ConnectForPlayer. The difference is that the second one will give you a reference to the player that just sent this event as the first parameter of the function. Here, as we want to know who wants to buy a hat, we are using ConnectForPlayer and we are just printing the name of the player. Paste that code inside the ShopServer script.
functionOnBuyHat(player)print("Received BuyHat from player "..player.name)
Now that we know when the player wants to buy a hat, we must check their resources. The first line is looking at the number of Coins of a player. If it is less than 3, then we can’t remove 3 Coins so we print an error and return the function, meaning that the rest of the code won’t be executed. If the condition is false, then we are using the RemoveResource function to update the number of coins and we print that action in the Event Log.
Start your game, pick 2 Coins, and try to buy the hat (it should write “Error: not enough coins”). Pick another Coin to reach 3 and try to buy the hat. Your 3 coins should be removed.
functionOnBuyHat(player)if player:GetResource("Coins") < 3thenprint("Error: not enough coins")
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.
3rd Party Cookies
This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.
Keeping this cookie enabled helps us to improve our website.
Please enable Strictly Necessary Cookies first so that we can save your preferences!