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

Object is "nil" even though it is there. How to fix it?

So, in a LocalScript I have a TextButton that is supposed to clone into a frame. Whenever I run the line:

local button = script.TextButton:Clone()

And I go into a server to to test, it gives me a client error. TextButton is not a valid member of LocalScript. I don't know why it is doing this. I checked the PlayerGui in game and it was there.

2 answers

✓ Accepted answer

The problem that is occurring is that the TextButton has not loaded in yet, so you are trying to reference to something that is nil (even though it may exist some time in the near future). To fix this, simply utilize the WaitForChild function of Instances like this:

local button = script:WaitForChild("TextButton"):Clone()

WaitForChild will yield your current thread until a child of the script with the name "TextButton" is found.

Try doing script:WaitForChild("TextButton") instead.

When working on LocalScripts, it is recommended to always use WaitForChild to access children (instead of other access functions such as the dot operator or FindFirstChild) so that the script is resilient to any loading issues.

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