如何修复“尝试用 nil 索引”

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

我正在尝试制作一个按钮,该按钮是您按下后传送的一部分,但是当按下它时,它会说:尝试使用“HummanoidRootPart”索引nil

我找不到任何关于如何具体解决我的问题的信息。

function click(x)
    local y = workspace:FindFirstChild(x).HumanoidRootPart.CFrame
    local location = script.Parent.Location.Position
    y = CFrame.new(location)
    print("Teleported")
end

script.Parent.ClickDetector.MouseClick:connect(click)

提前致谢

button roblox
2个回答
0
投票

当它显示“workspace:FindFirstChild(x)”时,workspace 找不到第一个名为“x”的子项。您使用 x 作为参数在工作区中查找,这没有意义,因为工作区:FindFirstChild 按名称查找对象。工作区找不到名为“x”的子项,或者工作区返回 nil,因为它试图查找不是字符串的内容,因此它返回“nil”,即“nil.HumanoidRootPart”,这是不允许的。

考虑这样做

function click()
    local y = workspace:FindFirstChild("nameOfObjectYouWantToFind").HumanoidRootPart.CFrame
    local location = script.Parent.Location.Position
    y = CFrame.new(location)
    print("Teleported")
end

script.Parent.ClickDetector.MouseClick:Connect(click)

记得将“nameOfObjectYouWantToFind”更改为您要查找的事物的名称。


0
投票

您需要在末尾添加

.Name
,因为
FindFirstChild()
检查字符串

function click(player)
    local y = workspace:FindFirstChild(player.Name).HumanoidRootPart.CFrame
    local location = script.Parent.Location.Position
    y = CFrame.new(location)
    print("Teleported")
end

script.Parent.ClickDetector.MouseClick:connect(click)
© www.soinside.com 2019 - 2024. All rights reserved.