2017-08-04 80 views
0

我試圖製作一個腳本,如果我在文本框中寫入名爲 的玩家在服務器中,他/她會死,但它給了我這個錯誤:嘗試索引文本框導致無值

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) 
+0

也許,而不是textBox使用TextBox? –

回答

3

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

此錯誤消息告訴你,你叫索引一個textBoxnil

所以去第一線,你指數textBox,這是這樣的:

textBox.FocusLost:Connect(function(enterPressed) 

爲什麼textBox中nil在這一行?那麼讓我們看看我們在該行之前的位置textBox

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

所以很明顯screenGui:FindFirstChild返回零。

請參閱參考手冊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的」,所以你不能找到一個參考手冊。

因此,首先,如果這可能是零,你可能想確保textBox不是你無需索引它。

if textBox then 
    textBox.someFancyIndex() 
end 

你已經這樣做了人形BTW:

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」的對象。你看錯了嗎?你忘了創建這個對象嗎?

這就是我們不能告訴你,因爲你沒有提供相應的代碼。

+1

他可能會嘗試方法:: WaitForChild()而不是FindFirstChild()。 Roblox不保證在腳本運行時加載資產。 – Henry