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

how do i run a function when a character is added to the world?

i need to define the players character as a variable and i need to wait until its added its giving me index nil "CharacterAdded" for the line that should run the code

local function GetDistance(p1,p2)
	local Distance = (p1.Position - p2.Position).magnitude
	return Distance
end
players = game:GetService("Players")
local function start()
	local character = players.LocalPlayer.Character.PrimaryPart
	local button = script.Parent
	while wait(0.1) do 
		if GetDistance(button - character) > 10 then
			print("E")
		end
	end
end


game.Players.PlayerAdded:Connect(function()	
	game.Players.LocalPlayer.CharacterAdded:Connect(start)
end)


2 answers

✓ Accepted answer

It's an easy fix don't worry! all you have to do is put the code in a server script in order to do it. Fun Fact: scripters use PlayerAdded to get to LocalPlayer on a server script. Hope this fix works!

inside the PlayerAdded event you need to pass the player joining as a parameter so game.Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(start) end) this should work

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