【问题标题】:Trying to index a TextBox results in a nil value尝试索引 TextBox 会导致 nil 值
【发布时间】:2018-01-12 07:02:41
【问题描述】:

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

尝试索引本地'textBox'(一个零值)

这是我的脚本:

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)

【问题讨论】:

  • 也许,用 TextBox 代替 textBox?

标签: lua textbox roblox


【解决方案1】:

尝试索引本地'textBox'(一个零值)

此错误消息告诉您正在索引一个名为 textBoxnil 值。

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

textBox.FocusLost:Connect(function(enterPressed)

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

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

显然 screenGui:FindFirstChild 返回 nil。

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

我们在这里读到:

返回找到给定名称的第一个孩子,如果没有,则返回 nil 孩子存在。如果可选的递归参数为真,递归 在搜索时下降层次结构,而不是仅搜索 直接对象。

所以根据参考手册,你没有一个名为“TextBlock”的孩子,所以你找不到。

首先,如果这可以为​​ 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”的对象。您是否在寻找错误的实例?你忘记创建那个对象了吗?

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

【讨论】:

  • 他可能会尝试方法 ::WaitForChild() 而不是 FindFirstChild()。 Roblox 不保证在脚本运行时加载资产。
猜你喜欢
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 2019-10-10
  • 2010-11-19
  • 1970-01-01
  • 2021-04-15
相关资源
最近更新 更多