Attempt to index nil with 'Text' – TextLabel text change script not working

The Gui I’m using only consists of one TextLabel.
The following samples are from the same server script:

tool.Equipped:Connect(function()
	gunUi = plr.PlayerGui.GunGui;
	gunLabel = gunUi:WaitForChild("display");
	gunUi.Enabled = true;
end);
gunLabel.Text = l.Value;

There seems to be no issues when gunUi is referenced in the script. However, when I try to modify the text of gunLabel, I get the “attempt to index nil with text” error. What could be the reason why the script has no issues with the Gui but with the label?

why is there ; in the end of every line?

Semi-colons are usually used in many other programming languages to tell the compiler it’s the end of the line, so it doesn’t cause unexpected errors. It’s not necessary at all in lua, but sometimes you just forget that you don’t need them, or you just prefer the sense of security.

Are you sure that gunLabel exists when you are referencing it, and is it the right name?

Yes, I did not write any other code that hinders the possibility of its existence, and it is the right name.

1 Like

Can I see the whole script? Maybe you’re just calling it when it hasn’t been defined yet.

tool.Equipped:Connect(function()
	gunUi = plr.PlayerGui.GunGui;
	gunLabel = gunUi:WaitForChild("display");
	gunUi.Enabled = true;
end);

while (wait(0.1)) do
	cd -= 0.1;
	if (cd <= 0) then
		cd = 0;
	end;
	if (cd == 0) then
		gunLabel.Text = l.Value;
	else
		gunLabel.Text = l.Value.." ("..cd..")";
	end;
end;

Skipped all irrelevant parts between the two parts of the code. These sections are the only parts where gunLabel is mentioned.

1 Like

Seems like you’re always trying to access gunLabel regardless of whether it’s been defined or not. You can simply just check if gunLabel exists in the first place:

if gunLabel then
	if (cd == 0) then
		gunLabel.Text = l.Value;
	else
		gunLabel.Text = l.Value.." ("..cd..")";
	end;
end

Also, for that bit of the code at the top of the while loop, you can just do cd = max(cd-1,0).

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.