如何修复“尝试用‘字符’索引 nil”(Roblox)

问题描述 投票:0回答:3

输出显示:

Players.username.PlayerGui.replicated:18: attempt to index nil with 'Character'

这是我的代码:

local Character = Player.Character or Player.CharacterAdded:Wait()

我该如何解决这个问题?

lua roblox
3个回答
1
投票

“尝试用...索引 nil”意味着 Player 为零,很可能是因为它尚未定义。

确保 Player 已被定义,如果它在 LocalScript 中运行,则可以使用

local Player = game:GetService("Players").LocalPlayer
script.Parent.Parent
来完成,因为您的脚本在 PlayerGui 中运行。

如果这不起作用,提供更大的代码片段可能有助于获得更好的答案。


1
投票

错误消息 attempts to index nil with 'someOtherName' 告诉您您正在执行以下操作之一:

someName.someOtherName
someName:SomeOtherName()
someName["SomeOtherName"]

其中

someName
是零值。不允许对 nil 值建立索引,因为它没有意义。您只能索引表值或具有 __index 元方法的值。

因此,当您遇到该错误时,请转到包含错误消息的行并查找执行该索引操作的任何表达式。现在您知道该 nil 值的名称了。是时候找出为什么它是零了。 要么修复这个问题,要么如果因为它发生在代码之外或者本来就是 nil 而无法修复它,请避免索引该 nil 值。例如使用 if 语句。


0
投票

本地玩家 = game.Players.LocalPlayer 本地角色 = 玩家.角色

script.Parent.Main.JoinMath.MouseButton1Click:Connect(function(AddPlayer)
    game.Workspace.Values.Players.Value = game.Workspace.Values.Players.Value + 1
end)

while wait() do
    if game.Workspace.Values.Players.Value == 0 then
        script.Parent.Main.PlayerAmount.Text = "2 Players Needed."
        game.Workspace.Values.Math.Value = false
    end
    
    if game.Workspace.Values.Players.Value == 1 then
        script.Parent.Main.PlayerAmount.Text = "1 Players Needed."
        game.Workspace.Values.Math.Value = false
    end
    
    if game.Workspace.Values.Players.Value == 2 or game.Workspace.Values.Players.Value >= 2 then
        script.Parent.Main.PlayerAmount.Text = "Starting Math Soon."
        wait(15)
        game.Workspace.Values.Math.Value = true
        if character:FindFirstChild("Humanoid") then
            character.Head.CFrame = CFrame.new(game.Workspace.Math.Position)
        end
    end
    
    --[[game.Workspace.Values.Math.Changed:Connect(function()
        if game.Workspace.Values.Math.Value == false then
            script.Parent.Main.Visible = true
        end
        
        if game.Workspace.Values.Math.Value == true then
            script.Parent.Main.Visible = false
        end
    end)]]--
end
© www.soinside.com 2019 - 2024. All rights reserved.