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

What is the problem with this script code?

I made a frame that follows the player's mouse, and then tryed adding a line that changes the Text of the TextLabel found in the frame. It gives this error in Output : "11:49:32.735 - Players.Player.PlayerGui.Info.Info.TestScript:6: attempt to index local 'target' (a nil value) 11:49:32.736 - Stack Begin 11:49:32.737 - Script 'Players.Player.PlayerGui.Info.Info.TestScript', Line 6 11:49:32.738 - Stack End"

And it has the code :

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local target = mouse.Target

while true do
	script.Parent.TextLabel.Text = "Name: " .. target.Name
	wait(0.1)
end

1 answer

✓ Accepted answer

Your Problem

Scripts are read from top to bottom. When you define your 'target' variable, on line 3, outside of your while loop, on line 5, then it makes it so the target variable is static. It will never change from what it was when the script first read line 3.

So to fix? Define it inside of the while loop. Also, I'd suggest adding a conditional just in case you're not pointing at anything at times.


Code

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

while wait(0.1) do
	local target = mouse.Target
	if target ~= nil then
		script.Parent.TextLabel.Text = "Name: " .. target.Name
	else
		script.Parent.TextLabel.Text = "Name: - - - -"
	end
end

1 comment

0

Thank you for helping!

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