Attempt To Index Nil With CashButtons

I am having an error with my Give Cash button. Inside the player there is a folder with a lot of BoolValues to check if the player already has received cash from that specific button.

Attempt to index nil with ‘CashButtons’ on line 3.

script.Parent.Touched:Connect(function(hit)
    local PlayerInPlayers = game.Players:GetPlayerFromCharacter(hit.Parent)
    if PlayerInPlayers.CashButtons.B5.Value == false then
        PlayerInPlayers.leaderstats["Cash"].Value = PlayerInPlayers.leaderstats["Cash"].Value + 10
        PlayerInPlayers.CashButtons.B5.Value = true
    end
end)

This happened if something that wasn’t a player touched your part. Simply check that the player exists beforehand.

local part = script.Parent
local Players = game:GetService("Players")

part.Touched:Connect(function(other)
    local player = Players:GetPlayerFromCharacter(other.Parent)

    if player and not player.CashButtons.B5.Value then
        player.leaderstats.Cash.Value = player.leaderstats.Cash.Value + 10
        player.CashButtons.B5.Value = true
    end
end)
1 Like