簡體   English   中英

Roblox Lua - 嘗試使用“stats”(leaderstats)索引 nil

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

我想做這個,當baseFinal被一個塊(Bloque)觸及時,它會給你錢並且塊被破壞。 它給了我一個錯誤:嘗試用'stats'索引nil

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) 

該錯誤告訴您plr變量未定義或為零。

由於此代碼在腳本中運行,因此問題在於您如何訪問播放器 object。 請參閱Players.LocalPlayer的文檔:

此屬性僅針對 LocalScripts(以及它們所需的 ModuleScripts)定義,因為它們在客戶端上運行。 對於服務器(Script 對象在其上運行其代碼),此屬性為零。

解決此問題的方法是通過另一種方式訪問播放器 object。 一種方法是連接到 Players.PlayerAdded 信號。

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)

這很可能是因為當您嘗試引用一個值時,您必須在其后面加上.Value才能更改值本身。 假設你有一個 stats 文件夾,你應該使用plr.stats.Value.Value代替。 下次,請向我們展示您的 object 結構,以便我們更好地了解錯誤是什么。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM