Hello! I have a script that is supposed to give you money each second you drive, but it isn't exactly working.
script.Parent.Touched:connect(touch) function touch(hit) local character = hit.Parent local stats = hit.Parent:findFirstChild("leaderstats") local player = game.Players:GetPlayerFromCharacter(character) local add = 110 wait(1) if character.HumanoidRootPart and script.Parent.SeatWeld then print("Player sitting") if script.Parent.Throttle == 1 then wait(1) local cash = stats:findFirstChild("Money") cash.Value = cash.Value +add end end end script.Parent.Touched:connect(touch)
It prints the player sitting message, but then comes up (and doesn't refer to any line in any script) saying attempt to call a nil value. Any ideas why it won't work? I have a leaderboard with a money section and everything.
Your problem with the script is the fact that the script can not find leaderstats in the character (Line 5). The leaderstats container is located in the player, which you do not find until line 6.
One thing that I do recommend you do for your script is, to detect if the hit part has a humanoid. As well as detect if the player variable had not returned nil if say, a model containing humanoid or a AI comes along and hits the brick.
Also, some of your spacing in your code is off. This progressive makes your code harder to read, by yourself and others. This may eventually lead you to forget or misplace ends for functions, loops, or if then statements.
local add = 110 --Amount of cash added when a player sits in the vehicle seat. function touch(hit) local character = hit.Parent local player = nil if character:FindFirstChild('Humanoid') then --So we will check if Humanoid is in the model hitting the part. player = game.Players:GetPlayerFromCharacter(character) --Now we are trying to get the player value. if player then if player:FindFirstChild('leaderstats') then --Now we're detecting if the leaderstats is in the player or not. --With a new property released in May you are able to use a property called SeatPart in Humanoid to detect the seat you're sitting in. while wait(1) and character and player do --It will wait 1 second, check if there is a character and player, if both the player and character are there, then the code will go. if character.Humanoid.SeatPart == script.Parent then if player.leaderstats:FindFirstChild('Money') then --Chk 4 meh m0ney. player.leaderstats.Money.Value = player.leaderstats.Money.Value + add end else --I know what you might be thinking. What if the SeatPart is nil? Well, we don't want the loop to go on forever, so we break it. break end end end end end end script.Parent.Touched:connect(touch) --We're connecting the function touch above this line.
(I'm a beginner scripter, so sorry if this doesn't work)
But the problem is that the nil value is add. The 14th line should be
cash.Value = cash.Value + 1
Hope this helps! Instead of add, put 1.