Well, its been a while since I scripted and now I'm rusty (not that I was any good before). I tried making a simple script that gives me an item in RepilcatedStorage when I press a TextButton. I successfully did it. I added a currency so I could deplete the points a character had if it decided to get a sword which cost 100 points. However, when I tried to tell the script to stop giving it to me once there was was already one in the backpack, it wouldn't work. I tried creating an if statement and I don't think I made it correctly. So here's the script I think will fix it. Did I do it right? Is there anything I can do to make my code cleaner?
Keep in mind the Item I'm cloning is in ReplicatedStorage and this local script is a child to the TextButton.
01 | script.Parent.MouseButton 1 Click:connect( function () |
02 | local player = game.Players.LocalPlayer |
03 | local sword = game.ReplicatedStorage.ClassicSword |
04 | local points = player.leaderstats.Points.Value |
05 | local bought = false |
06 | if points.Value > 0 then |
07 | local newsword = sword:Clone() |
08 | newsword.Parent = player.Backpack |
09 | local bought = true |
10 | else |
11 | print ( "Already owned or insufficient funds" ) |
12 | bought = true |
13 | end |
14 | end ) |
You just need to add a couple of checks:
01 | --move these to the beginning so you arent running them everytime the event fires |
02 |
03 | local player = game.Players.LocalPlayer |
04 | local sword = game:GetService( "ReplicatedStorage" ):WaitForChild( "ClassicSword" ) |
05 | local points = player:WaitForChild( "leaderstats" ):WaitForChild( "Points" ) --omitted value property |
06 |
07 | script.Parent.MouseButton 1 Click:connect( function () |
08 | if points.Value > 0 and player.Backpack:FindFirstChild(sword.Name) = = nil and player.Character:FindFirstChildOfClass( "Tool" ) = = nil then |
09 |
10 | --the first one i added checks the backpack, and the second makes sure a tool isnt in the character (where tools go when equipped) |
11 |
12 | local newsword = sword:Clone() |
13 | newsword.Parent = player.Backpack |
14 | else |
15 | print ( "Already owned or insufficient funds" ) |
16 | end |
17 | end ) |
You might put those two checks in a new line, since it looks kind of messy.
Accept and upvote if this helps!