How would I go about making an optimized npc follow script?

So I’m tryna make something where a dragon npc follows around a player, like a pet almost you’d see in pet sim x.

It works and everything but when there is multiple players with multiple dragons following people around, it for some reason slows down the game by alot. For example a timer, it would slow down the timer by 2x and basically break the whole game.

How would I get around this?

local Players = game:GetService("Players")

while true do
	if script.Parent.Player.Value == nil then
		--no player to follow
	else
		local char = script.Parent.Player.Value
		local plr = Players:GetPlayerFromCharacter(char)

		if plr:WaitForChild("PlayerData").Sitting.Value == false then
			script.Parent.Humanoid:MoveTo(char:WaitForChild("HumanoidRootPart").Position + Vector3.new(0,0,5))
		end
	end

	wait(0.1)
end

the Player.Value thingy is a object value in the dragon model itself that gets the player, once the player is assigned to that dragon.

1 Like

Instead of using Humanoid:MoveTo(), try studying and using AlignPosition and AlignOrientation. They are useful in this case as it doesn’t require scripting the pet itself to follow the player and instead let physics do the job.

1 Like

I recommend using :GetPropertyChangedSignal('Position') instead of that while true do.

If I’m not mistaken, doesn’t this event only fire when you explicitly set the part’s position? I always thought that the physics engine made a point of never firing a property change for position and rotation because of performance. In that case, you’d have to poll for property changes at set intervals rather than listening for a changed event.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.