Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Attempt to index global (a nil value) help?

I'm making a search system in my game where you search something (in this case a desk) and you get whatever is inside the desk. Here's the code:

get = game.Workspace.Get
searchtime = script.Parent.SearchTime.Value
contents = script.Parent.Contents.Value
target = workspace:FindFirstChild(script.Parent.Contents.Value)

get.Changed:connect(function()
	if get.Value == "Player" then
		script.Parent.Contents.Value = "Matches"
		script.Parent.What.Value = "Searching Desk..."
		script.Parent.TextLabel.Text = script.Parent.What.Value
		script.Parent.TextLabel.Visible = true
		wait(searchtime)
		script.Parent.TextLabel.Visible = false
		target.Value = target.Value + 5
	end
end)

"Get" is just a trigger value that when changed, this script fires. So basically, it sets the contents to "Matches", waits the searchtime value, then sets "target" to the contents value. Target is what i believe to be the problem. Using FindFirstChild, i have it find the contents value inside workspace. In this case, its matches. There is a "Matches" Value inside workspace which is the value holding the total matches the player has. The target finds the "Matches" value, then changes the value. This is where Output is telling me I have done something wrong. Output says: "Attempt to index global "target" (a nil value).

All help is greatly appreciated.

1 answer

✓ Accepted answer

You need to define target again as the target variable would be nil if the contents value was nil beforehand.

Also, try to use local variables when you can. They're faster to obtain than global variables.

local get = game.Workspace.Get
local searchtime = script.Parent.SearchTime
local contents = script.Parent.Contents
local target = workspace:FindFirstChild(script.Parent.Contents.Value)

get.Changed:connect(function()
    if get.Value == "Player" then
		contents.Value = "Matches"
		script.Parent.What.Value = "Searching Desk..."
		script.Parent.TextLabel.Text = script.Parent.What.Value
		script.Parent.TextLabel.Visible = true
		target = workspace:FindFirstChild(contents.Value) --Update the target variable. We don't need to use local again since we've already defined the variable.
		if not target then return end --If target is not available, return end.
		wait(searchtime.Value)
		script.Parent.TextLabel.Visible = false
		target.Value = target.Value + 5
	end
end)

I hope my answer helped you. If it did, be sure to accept it.

1 comment

0

Yep, it worked! Thank you!

This discussion is preserved as it was. New answers, comments, and votes are closed.