Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 3 years ago

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

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

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!

Ad
Log in to vote
0
Answered by 3 years ago

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

Answer this question