尝试索引一个 TextBox 会导致 nil 值

我试着制作一个脚本,如果我在一个 TextBox 中写入一个在服务器中的玩家的名字,他/她会死亡,但是它给了我这个错误:

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

这是我的脚本:

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

textBox.FocusLost:Connect(function(enterPressed)
  --[[每当 TextBox 失去焦点时,就会调用此函数。当玩家在其中输入文本时,TextBox 处于“聚焦”状态,当他们进行其他操作时,则处于“非聚焦”状态。]]
  --[[此函数会传递一个参数“enterPressed”。如果玩家通过按下回车键使 TextBox 失去焦点,则该值为 true。还有一种使其失去焦点的方法是在其外部单击某处。]]

  --尝试查找一个名为 TextBox 中任何内容的玩家
  local player = game.Players:FindFirstChild(textBox.Text)
  if player then --检查是否找到了该玩家
    local character = player.Character
    local humanoid = character:FindFirstChild("Humanoid") --尝试找到 humanoid

    if humanoid then --检查是否找到了该 humanoid
      humanoid.Health = 0 --杀死该 humanoid
    end
  end
end)
点赞
用户2858170
用户2858170

错误信息

尝试索引局部变量'textBox'(未设置值)。

这个错误信息告诉你正在索引一个名为textBoxnil值。

所以,去找到你索引textBox的第一行,就是这一行:

textBox.FocusLost:Connect(function(enterPressed)

为什么在这一行中textBoxnil?好吧,我们看看在该行之前将值分配给textBox的位置。

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

所以很明显,screenGui:FindFirstChild返回了nil

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

在这里,我们可以看到:

返回第一个带有给定名称的子属性,如果没有这种子属性,则返回nil。 如果递归参数是 true,则在搜索时递归降层次结构,而不仅搜索直接对象。

所以根据参考手册,你没有一个名为“TextBlock”的子属性,因此你无法找到一个。

所以首先,如果可能为空,你可能要确保在索引它之前textBox不是nil

if textBox then
  textBox.someFancyIndex()
end

顺便说一下,你已经在寻找* humanoid *时这样做:

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”的对象。你是在错误的实例中寻找吗?你忘记创建那个对象了吗?

这是我们不能告诉你的,因为你没有提供相应的代码。

2017-08-04 11:54:17