试图索引一个 TextBox 导致一个 nil 值

Trying to index a TextBox results in a nil value

我试着制作一个脚本,如果我在文本框中写一个名字 服务器 he/she 中的玩家会死,但它给我这个错误:

attempt to index local 'textBox' (a nil value)

这是我的脚本:

local screenGui = script.Parent
local textBox = screenGui:FindFirstChild("TextBox", true)

textBox.FocusLost:Connect(function(enterPressed)
  --[[This function is called every time the TextBox is "unfocused". A TextBox is "focused" when the player is typing in it, and "unfocused" when they're doing something else.]]
  --[[a parameter is passed to this function, "enterPressed". This is true if the player unfocused the TextBox by pressing enter. Another way to unfocus it is by clicking somewhere outside it.]]

  --Try to find a player with the name of whatever is in the TextBox
  local player = game.Players:FindFirstChild(textBox.Text)
  if player then --Check if we found that player
    local character = player.Character
    local humanoid = character:FindFirstChild("Humanoid") --try to find the humanoid

    if humanoid then --check if we found that humanoid
      humanoid.Health = 0 --kill the humanoid
    end
  end
end)

attempt to index local 'textBox' (a nil value)

此错误消息告诉您正在索引一个名为 textBox.

nil

所以转到索引 textBox 的第一行:

textBox.FocusLost:Connect(function(enterPressed)

为什么文本框 nil 在这一行?好吧,让我们看看我们在哪里为该行之前的 textBox 赋值。

local textBox = screenGui:FindFirstChild("TextBox", true)

很明显screenGui:FindFirstChild returns nil.

参考参考手册http://wiki.roblox.com/index.php?title=API:Class/Instance/FindFirstChild&redirect=no

这里我们读到:

Returns the first child found with the given name, or nil if no such child exists. If the optional recursive argument is true, recursively descends the hierarchy while searching rather than only searching the immediate object.

因此根据参考手册,您没有名为 "TextBlock" 的 child,因此您找不到。

所以首先,如果这可以为​​ nil,您可能需要确保 textBox 在索引之前不为 nil。

if textBox then
  textBox.someFancyIndex()
end

顺便说一句,你已经为类人动物做了这个:

local humanoid = character:FindFirstChild("Humanoid") --try to find the humanoid

if humanoid then --check if we found that humanoid
  humanoid.Health = 0 --kill the humanoid
end

那么为什么不使用 textBox?

那你当然要弄清楚为什么你没有一个名为"TextBox"的object。你在找错实例吗?您是否忘记创建 object?

由于您没有提供相应的代码,因此我们无法告诉您。