Attempt to index nil with 'Character'

Hi,
It says Attempt to index nil with ‘Character’ IDK what to do, here is the script:


local function colorChange(player)
	wait(2)
	local char = player.Character or player.CharacterAdded:Wait(0)
	script.Parent["Body Colors"]:Clone().Parent = char
	wait(1)
	char:Destroy()
end

Thanks for all help
Btw Im still a beginner at programming

May I ask where is this code being placed and where does it get called from?

“Attempt to index nil with character” means trying to get the character of nil.

Or in simple terms, player is nil

You have to check if the character even exists. To do this you have to make an if statement.

local function colorChange(player)
	wait(2)
	local char = player.Character or player.CharacterAdded:Wait(0)
	if char then
		script.Parent["Body Colors"]:Clone().Parent = char
		wait(1)
		char:Destroy()
	end
end

Tell me if it works!

you can modify the code to handle the case where ‘player.Character’ is nil by using a conditional statement. like so:

local function colorChange(player)
	wait(2)
	local char = player.Character or player.CharacterAdded:Wait(0)
	script.Parent["Body Colors"]:Clone().Parent = char
	wait(1)
	char:Destroy()
end

In this code, the ‘if char then’ statement checks if the ‘char’ variable is not nil before continuing with the rest of the code. If ‘char’ is nil, the function will exit without trying to clone the body colors or destroy the character.

Its called with

script.Parent.Activated:Connect(colorChange)

and its placed in a normal script and its the only code.

Activated does not pass player as an argument.
image

1 Like

You can get the player who is controlling the tool by…
server
player = game.Players:GetPlayerFromCharacter(tool.Parent)
client
player = game.Players.LocalPlayer

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.