I have a script that won’t print a stud distance from my door. I’m unsure why it doesn’t give me any errors.
SCRIPT:
--PLAYER VARIABLES
local PLR = game.Players.PlayerAdded:Wait()
local CHR = PLR.Character or PLR.CharacterAdded:Wait()
--PART VARIABLES
local PrmPart = script.Parent.Carpet -- The carpet is the PrimaryPart, or the PartVector
--VECTOR VARIABLES
local PLRVector = Vector3.new(CHR:WaitForChild("HumanoidRootPart").Position) --Player's Vector3
local PARTVector = Vector3.new(PrmPart.Position)
--MAGNITUDES
local Mag = (PLRVector - PARTVector).Magnitude -- Magnitude
--CODE
while true do
wait(0.5)
print(Mag .. " studs from the door.") --Prints the magnitude distance
end
One problem is that you are never going to get a different number because you are only calculating once, so every print will say the same thing. You will have to put the magnitude calculation and re-get the positions in the while true do in order for anything to change.
Alright, make a script in StarterCharacterScripts and put the following code:
local char = script.Parent
local carpet = workspace:WaitForChild("Door"):WaitForChild("Carpet")
game:GetService("RunService").Heartbeat:Connect(function()
local Mag = (char:FindFirstChild("HumanoidRootPart").Position - carpet.Position).Magnitude
print(Mag .. " studs from the door.")
end)
The issue with your script is the way you find the players character, and you don’t ever update the variables with new information, but my script fixes that issue.
Also while true loops with waits are bad. A heartbeat loop runs every frame and has no delay.
local Players = game:GetService("Players");
local PrmPart = script.Parent:WaitForChild("Carpet");
local function on_char_added(character)
while character.PrimaryPart.Parent do
local dist = (character.PrimaryPart.Position - PrmPart.Position).Magnitude;
print(dist .. " studs from the door.");
task.wait(0.5);
end
end
Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(on_char_added);
end)
Above code should suit your needs. To detect new players, use Players.PlayerAdded event, similarly use player.CharacterAdded for detecting character being added. Run a while loop while the character exists, calculating the magnitude every 0.5 seconds (using task.wait(), as it is more accurate).
It works. The only issue is that you forgot to put .Position for the Character primary part. Thanks anyway, I have to start using functions a lot more.