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

Error: Attempt to index local 'player' (a nil value) HELP! (?)

I'm trying to modify some gui texts through a normal script located in workspace but when I test it i got the error: Attempt to index local 'player' (a nil value). I know this would not happen if i use a script inside the gui and put that Player = script.Parent.Parent.Parent but for some reasons i don't want to do it that way. Here's how the code looks like:

player = game.Players.LocalPlayer
PlyrGui = player.PlayerGui -- Here is the error ('player' (a nil value) )
Gui1 = PlyrGui:WaitForChild("Menu1")

function Action1()
-- Imagine here is all the funciton. lol
end

game.Players.ChildAdded:connect(Action1)

How I can make the computer find the player so then it can find the playerGui? Please help

1 answer

This will not work, since only LocalScripts have access to LocalPlayer.

But, a much better function to use to fix this would be:

game.Players.PlayerAdded:connect(function(player)
	local PlyrGui = player.PlayerGui
	local Gui1 = PlyrGui:WaitForChild("Menu1")
	-- code
end)

EDIT: Using a function, not just when a player spawned.

To do this, a script like this would be helpful:

function editGui(player,objectName,screenGuiName,text) -- player, objectName (name of the object you're looking for), screenGuiName (ScreenGui that is an ancestor of object)
	local gui = player.PlayerGui:FindFirstchild(screenGuiName)
	if gui then
		local obj = gui:FindFirstChild(objectName,true) -- the second parameter is whether it will search through descendants, instead of children (descendants includes children).
		if obj then
			obj.Text = text
		end
	end
end

If you want this to happen to all players at the same time, change the playerAdded function to this:

local players = {} -- put this on Line 1 of script

game.Players.PlayerAdded:connect(function(player)
	players:insert(player)
end)

game.Players.PlayerRemoving:connect(function(player)
	players:remove(player)
end)

for _,v in pairs (players) do
	editGui(v,"MenuText1","Menu1","HELLO!") -- looks for an object named "MenuText1", inside "Menu1", which is inside the player's playerGui, and changes it's text to "HELLO!"
end

Hope I helped :)

1 comment

0

But I want to use this function not just when a player joins the game :(

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