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

why cant i get the character of a player?

i want to make a brick that copies the brickcolor of the players head but i cant access the character from the brick.

brick script:

local player = game.Players.LocalPlayer
local char = player.Character
local brick = script.Parent

brick.BrickColor = char.Head.BrickColor

my output keeps saying 13:06:09.733 - Workspace.Part.Script:1: attempt to index nil with 'Character'

can someone please explain how i can get to the character?

1 answer

✓ Accepted answer

That is because the server does not know which player and character its supposed to use. In other words, you can't use game.Players.LocalPlayer in server scripts.

There are many possible solutions to this problem. The one I will provide is not very efficient, but should solve your problem. If you have many bricks like this, copying this script over and over may introduce significant lag.

So lets assume the brick will change colour with the nearest character head colour and that it will update nearest character every second. You may of course update more often, but beware of the aforementioned lag.

local brick = script.Parent


while true do --infinite loop
	
	local shortestMagnitude = 100000 --put big number here
	local nearestHead = nil

	--loop through all players
	for _, player in pairs(game.Players:GetPlayers()) do
		
		--check if player has character loaded
		if player.Character then
			
			local head = player.Character:FindFirstChild("Head")
			if head then

				if (head.Position - brick.Position).Magnitude < shortestMagnitude then
					
					shortestMagnitude = (head.Position - brick.Position).Magnitude
					nearestHead = head

				end

			end

		end

	end
	
	if nearestHead then
		brick.Color = nearestHead.Color
	end
	wait(1)

end		

Please read about Touched event, as it may be better solution for this problem.

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