Networked Event: Buying an item

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.

function OnBuyHat(button)
    if PLAYER:GetResource("Coins") < HAT_PRICE then
        print("Not enough coins")
endCode language: Lua (lua)

Receive event

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).

ShopServer is server-side, UIShop is client-side

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.

function OnBuyHat(player)
    print("Received BuyHat from player "

Events.ConnectForPlayer("BuyHat", OnBuyHat)Code language: Lua (lua)

Resources Logic

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.

function OnBuyHat(player)
    if player:GetResource("Coins") < 3 then
        print("Error: not enough coins")
    player:RemoveResource("Coins", 3)
    print("Removed coins")

Events.ConnectForPlayer("BuyHat", OnBuyHat)Code language: Lua (lua)
Post a comment

Leave a Comment

Scroll to Top