Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What is the problem with this script code?

Asked by 8 years ago

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

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

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
0
Thank you for helping! User#9483 0 — 8y
Ad

Answer this question