Basically I want to click on a model that’ll then dissapear and give you money yet I get the error saying taht they’re trying to attempt the field “leaderstats” a nil value, here is the script
01 | function OnClick() |
02 | |
03 | local player = game.Players:GetPlayers() |
04 | |
05 | for i = 1 ,#player do |
06 | |
07 | if (player [ i ] :FindFirstChild( "leaderstats" ) ~ = nil ) then |
08 | |
09 | local clicks = player [ i ] .leaderstats.Money |
10 | |
11 | if (clicks ~ = nil ) then |
12 | |
13 | player.leaderstats.Money.Value = player.leaderstats.Money.Value + |
14 | 250 |
15 | |
16 | script.Parent.Box.CanCollide = false |
17 | |
18 | script.Parent.Box.Transparency = 1 |
19 | |
20 | script.Parent.TV 3. CanCollide = false --Change COUCH to the name |
21 | of your model! |
22 | |
23 | script.Parent.TV 3. Transparency = 1 -- same here |
24 | |
25 | wait( 60 ) -- Change this to the amount of time you want until it |
26 | respawns (can be any number) |
27 | |
28 | script.Parent.Box.CanCollide = true |
29 | |
30 | script.Parent.Box.Transparency = 1 |
31 | |
32 | script.Parent.TV 3. CanCollide = true -- change COUCH to the name |
33 | of your model ! |
34 | |
35 | script.Parent.TV 3. Transparency = 0 -- same here |
36 | |
37 | end |
38 | |
39 | end |
40 | |
41 | end |
42 | |
43 | end |
44 | |
45 | |
46 | |
47 | script.Parent.ClickDetector.MouseClick:connect(OnClick) |
The reason you’re getting that error is because the variable “player” is defined as a table of all the players in the server, not just a single player. You already have a variable that is defined as the players money, so you can replace line 13 with:
1 | clicks.Value = clicks.Value + 250 |
After fixing this I believe that your code rewards every player in the server with money, not just the player who clicked the model which I believe this is not what you want. To fix this you can recreate your function with a “playerWhoClicked” parameter instead. For example:
01 | local function OnClick(player) |
02 | local money = player.leaderstats.Money |
03 | money.Value = money.Value + 250 |
04 | local objects = script.Parent:GetChildren() |
05 | for i = 1 , #objects do |
06 | local object = objects [ i ] |
07 | if object:IsA( "BasePart" ) then |
08 | object.Transparency = 1 |
09 | object.CanCollide = false |
10 | end |
11 | end |
12 | wait( 60 ) |
13 | for i = 1 , #objects do |
14 | local object = objects [ i ] |
15 | if object:IsA( "BasePart" ) then |
16 | object.Transparency = 0 |
17 | object.CanCollide = true |
18 | end |
19 | end |
20 | end |
21 | script.Parent.ClickDetector.MouseClick:Connect(OnClick) |
For other information about ClickDetector.MouseClick, you can visit this page:
https://developer.roblox.com/api-reference/event/ClickDetector/MouseClick