I'm working on a Gui script which works perfectly when I run it in test mode but then when I run it in a server I get the is error: "Players.Player1.PlayerGui.ScreenGui.MapMenu.Maps.Kamino.Loc:2: attempt to index a nil value" Am I doing the 'FindFirstChild' function correctly? I've had a friend who is more advanced at scripting take a look at it and they said the couldn't spy any errors.
local pic = script.Parent.Parent.Parent:FindFirstChild("Pic") local info = script.Parent.Parent.Parent:FindFirstChild("Info").info local n = script.Parent.Parent.Parent:FindFirstChild("Info").Title local place = script.Parent.Parent.Parent:FindFirstChild("Menu").Enter.LocalScript.PlaceID local LS = script.Parent.Parent.Parent:FindFirstChild("Menu").Enter.LocalScript function onClicked(GUI) LS.Disabled = false pic.Image = "http://www.roblox.com/asset/?id=209567993" n.Text = "Tatooine: Mos Eisley" info.Text = "'Mos Eisley Spaceport. You will never find a more wretched hive of scum and villainy. We must be cautious.' - Ben Kenobi to Luke Skywalker" place.Value = 191123707 end script.Parent.MouseButton1Click:connect(onClicked)
:FindFirstChild
can return nil
. That's when the child doesn't exist.
Say there's an object in the workspace called "Apple" and I want to change its color
local apple = workspace.Apple apple.BrickColor = BrickColor.red()
If there isn't an object named "Apple", then when I do workspace.Apple
, I will get an error saying there is no such thing.
I could instead use :FindFirstChild
:
local apple = workspace:FindFirstChild("Apple")
Now, I won't get any error. But apple
is nil
, so if I try to do something to it:
apple.BrickColor = BrickColor.red()
I will get an error.
If you're going to use :FindFirstChild
, you have to have a plan of what to do when the object doens't exist -- otherwise you should just use .
since it's a lot shorter and clearer.
if not apple then -- if apple ~= nil then apple.BrickColor = BrickColor.new() else -- I can't do anything. end
In your case, it looks like you're expecting there to be something there. In that case, you should probably use :WaitForChild
.
:WaitForChild
is similar to :FindFirstChild
, except that it is guaranteed to never return nil
-- it does this by waiting until there is an object that it can return.
If :WaitForChild
isn't a solution, probably you are either looking in the wrong place (wrong script.Parent
, etc) or the object is actually named something else (capitalization counts, etc)