简体   繁体   中英

Roblox Lua - attempt to index nil with 'stats' (leaderstats)

i want to make this, when the baseFinal is touched by a block (Bloque) it gives you money and the block is destroyed. it gives me an error: attempt to index nil with 'stats'

local base = script.Parent.Base

local baseFinal = script.Parent.Final

local plr = game.Players.LocalPlayer


baseFinal.Touched:Connect(function(hit)
    
    if hit.Name == "Bloque" then
        wait(0.6)
        plr.stats.Value = plr.stats.Value + 5  // here is the error
        hit:Destroy()
    end
     
end) 

The error is telling you that the plr variable is undefined or nil.

Since this code is running in a Script, the issue is how you are accessing the Player object. See the documentation for Players.LocalPlayer :

This property is only defined for LocalScripts (and ModuleScripts required by them), as they run on the client. For the server (on which Script objects run their code), this property is nil.

The way to fix this is to access the Player object another way. One way is to connect to the Players.PlayerAdded signal.

local base = script.Parent.Base
local baseFinal = script.Parent.Final

local connections = {}

game.Players.PlayerAdded:Connect( function(plr)
    -- listen for Players to touch the block
    local connection = baseFinal.Touched:Connect( function(hit)
        if hit.Name == "Bloque" then
            wait(0.6)
            plr.stats.Value = plr.stats.Value + 5
            hit:Destroy()
        end
    end)

    -- hold onto the connection to clean it up later
    connections[plr] = connection
end)

-- clean up when the Player leaves
game.Players.PlayerRemoving:Connect( function(plr)
    connections[plr]:Disconnect()
end)

This is most likely because when you are trying to reference a value, you must put .Value after it in order to change the value itself. Assuming you have a stats folder, you should use plr.stats.Value.Value instead. Next time, please show us your object structure so we have a better understanding of what the error is. Thanks.

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