Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Someone please help me!! I can't change the cash value! I keep getting an error?

Asked by 7 years ago

So, apparently, when a brick touches another one, I want the cash to change from the current + 25, but i get this error: 18:51:02.429 - Workspace.Full Tycoon.Red.ConveyorBelt.Part.Script:1: attempt to index field 'LocalPlayer' (a nil value). Some one please help!!

local money = game.Players.LocalPlayer:WaitForChild("leaderstats"):FindFirstChild("Cash")
script.Parent.Touched:connect(function(hit)
    if hit.Name == "Basic" then
        money.Value = money.Value + 25
        hit:remove()
    end
end)

1 answer

Log in to vote
0
Answered by
Azarth 3141 Moderation Voter Community Moderator
7 years ago
Edited 7 years ago

The problem is that you're trying to access LocalPlayer from a normal script. The script has no idea who the current player is, which is why LocalScripts are placed in a location that is a descendant of the player.

From the Wiki: A LocalScript will only run Lua code if it is a descendant of one of the following objects:

A Player's Backpack, such as a child of a Tool

A Player's Character model

A Player's PlayerGui

A Player's PlayerScripts

The ReplicatedFirst service*

You could run this in a LocalScript in one of those locations.

local player = game.Players.LocalPlayer
local stats = player:WaitForChild("leaderstats")
local cash = stats:WaitForChild("Cash")
local brick = Workspace:WaitForChild("Your brick")

print("Everything loaded") -- If this doesn't print, fix above.

local last
brick.Touched:connect(function(hit)
    if hit and hit.Name == 'Basic' then 
        if last and last == hit then print("Don't duplicate cash") return end
        cash.Value = cash.Value + 25
        hit:Destroy()
        last = hit
    end
end
Ad

Answer this question