简体   繁体   中英

attempt to index nil with 'TookMoney'

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

me.Touched:Connect(function(Hit)
    local player = players:GetPlayerFromCharacter(Hit.Parent)
    if player.TookMoney.Value == true then
        player.TookMoney.Value = false
    end
end)

It has to make TookMoney.Value = false but it says "attempt to index nil with 'TookMoney' -script:6"

The touched event is triggered on all objects, including non players. Thus players:GetPlayerFromCharacter can return nil. Perform a nil check, eg:

me.Touched:Connect(function(Hit)
    local player = players:GetPlayerFromCharacter(Hit.Parent)
    if player and player.TookMoney.Value == true then
        player.TookMoney.Value = false
    end
end)

Depending on your setup you may also check if the player has TookMoney .

local Players = game:GetService("Players")
local BasePart = script:FindFirstAncestorWhichIsA("BasePart")

BasePart.Touched:Connect(function(hit)
    local character = hit.Parent
    if character:IsA("Model") then
        local player = Players:GetPlayerFromCharacter(character)
        if player then
            local tookMoney = player:FindFirstChild("TookMoney")
            if not tookMoney then
                tookMoney = Instance.new("BoolValue", player)
            end
            tookMoney.Value = false
        end
    end
end)

You should validate that the character is a Player by using the method provided by the API's Players service. Furthermore, you should also consider creating a new BoolValue for a scenario in which the ValueBase is not available.

Keep in mind that checking for boolean states on objects that you are going to change based on said state is quite literally pointless, so when something is true in order for something to be false , ignore the first bit that is validating the discrepancy.

Here's an example:

Do not do this:

if x == true then
    x = false
end

Do this:

x = false

If it is ever necessary that you need to check a condition in order for something to be true / false , make sure that the material that you are validating is not the same material you are changing.

So for example, if x is not y , then make x = y . But in the case where x is not 0 , just directly set x as 0 , rather than checking if x ~= 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM