I’m working on a script that allows the Players pet to follow them. This loop is run in the server and our servers are from 40-50 people so after a while I think this might put some stress on the server. Is there anything else I can do differently to prevent this?
(Code runs perfectly)
local Player = game:GetService('Players'):GetPlayerFromCharacter(script.Parent)
local ReplicatedStorage = game:GetService('ReplicatedStorage')
local myStat = ReplicatedStorage:WaitForChild('PlayerValues'):WaitForChild('uid_'..Player.UserId)
local Pets = myStat:WaitForChild('Pets')
local MyPets = {}
for _, pet in next, Pets:GetChildren() do
if pet.Owned.Value == true and pet.Equipped.Value == true then
local a = pet.Model:Clone()
a.Parent = Player.Character
table.insert(MyPets, a)
end
end
while true do
wait()
local character = Player.Character
if character then
if character.Humanoid.Health >= 0 then
for _, pet in next, MyPets do
if pet then
pet:SetPrimaryPartCFrame(character.HumanoidRootPart.CFrame * CFrame.new(2,2,2))
end
end
end
end
end
If you have round 40 to 50 players on a server, I highly discourage you from setting up a loop running at 30hz for every single player. This can cause severe server lag.
Furthermore, frequently updating the CFrame is somewhat unsmooth and signal latency will make the whole thing look very jumpy.
Instead, try the following:
Have a server script set the pet’s network ownership to the player upon equip.
Insert a BodyGyro and a BodyPosition into the pet’s root part.
Have a local script update these frequently.
You can update the BodyMovers either on a RunService.Heartbeat basis, or even doing so on a loop at 10hz would be totally fine. The pet will accelerate & decelerate as the player moves to make things smooth.
Like so
local char = script.Parent
local pet = PathToPet
local gyro = PathToBodyGyro
local pos = PathToBodyPosition
local hroot = char.PrimaryPart
while wait(.1) do
gyr.CFrame = hroot.CFrame
pos.Position = hroot.CFrame * Vector.new(2, 2, 2)
end
Honestly, if you’re doing it how you’re doing it right now you’re better off welding the pet to the character. The weld would do exactly what you’re doing but without the overhead of a script running. Unless you plan on animating the pet by making it wiggle and/or walk to its new position, its entirely unnecessary to run a loop for this.
Additionally, if the character ever flips upside-down or do some wacky dance moves on the floor your pet will flip upside-down and be in the air. This would be the same thing that would happen if you welded it as well, though.