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

Why is this script breaking?

So, the logic behind this script is that it is in a brick. When a player steps on the brick, it creates a cloned gui from lighting and places it in the player's PlayerGui. There is a bool value in the player so that if the gui is already opened, it won't clone it again. The problem is that the script breaks at line 7 giving the error "Workspace.Teleport Place 1.Part.Script2:7: attempt to index field 'LocalPlayer' (a nil value)" In my previous experiences, I've always had trouble with "nil values". What is the problem with this script?

function onTouch(part)

local human = part.Parent:findFirstChild("Humanoid")

if (human ~= nil) then

if game.Players.LocalPlayer.TeleP1.Value == false then
	
game.Lighting.TeleP1:clone().Parent = game.Players.LocalPlayer.PlayerGui

game.Players.LocalPlayer.TeleP1.Value = true

else
	
print("Already Open.")
	
wait(1)

end 
end 
end

script.Parent.Touched:connect(onTouch)

1 comment

0

LocalPlayer will only work in a LocalScript. LocalScripts will only work in the Player's Backpack, PlayerGui, Character, or PlayerScripts.

2 answers

Use the GetPlayerFromCharacter function of players.

-- Regular script
function onTouch(part)
	local human = part.Parent:FindFirstChild("Humanoid")
	local plr = game.Player:GetPlayerFromCharacter(part.Parent)
	if human and plr then
		if plr.TeleP1.Value == false then
			game.Lighting.TeleP1:clone().Parent = plr.PlayerGui
			plr.TeleP1.Value = true
		else
			print("Already Open.")
			wait(1)
		end 
	end 
end

script.Parent.Touched:connect(onTouch)

Things I Changed,

  • I changed findFirstChild to FindFirstChild

findFirstChild is deprecated, and/or it's just bast to use capital letters.

  • I used GetPlayerFromCharacter function

Local Scripts don't work in workspace, and scripts can't use LocalPlayer.

  • I tabbed your code correctly

You're welcome.


Optional changes,

While Filtering Enabled is Enabled, scripts can't access PlayerGui. To make this FE compatible, use RE or use a Local Script in StarterPackor something, with the proper variables re-defined without using .Parent of course.

I hope I helped!

Good Luck!

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