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 4 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

01local function GetDistance(p1,p2)
02    local Distance = (p1.Position - p2.Position).magnitude
03    return Distance
04end
05players = game:GetService("Players")
06local function start()
07    local character = players.LocalPlayer.Character.PrimaryPart
08    local button = script.Parent
09    while wait(0.1) do
10        if GetDistance(button - character) > 10 then
11            print("E")
12        end
13    end
14end
15 
16 
17game.Players.PlayerAdded:Connect(function()
18    game.Players.LocalPlayer.CharacterAdded:Connect(start)
19end)

2 answers

Log in to vote
1
Answered by 4 years ago
Edited 4 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 4 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