Need help with scripting issue

I want to achieve a system where if a player is out of range from NPCs then the NPCs are moved to replicated storage & when back in range the NPCs are moved back to the workspace. This is to stop too many NPCs from lagging the game.

The issue is when muliple players are in the game. if one player is out of range it tries to put the NPCs in the replicated storage but if another player is in range it tries to put it in the workspace, so it causes lag and error since it is constantly moveing the NPCs back and to.

Here is the Script:

NPC Code.txt (2.7 KB)

1 Like

Can you paste the code here so i can assist you, i do not click on links/downloads for security reasons.

1 Like

local distanceThreshold = 550 – Adjust this value as needed

local replicatedStorage = game:GetService(“ReplicatedStorage”)

local function getDistance(position1, position2)
return (position1 - position2).magnitude
end

local function moveNPCToReplicatedStorage(npcFolder)
npcFolder.Parent = replicatedStorage.NPCsStorage
end

local function moveNPCToOriginalFolder(npcFolder)
npcFolder.Parent = workspace.NPCs
end

local function manageNPCsForPlayer(player)

local character = player.Character
local humanoidRootPart = character and character:FindFirstChild("HumanoidRootPart")

if humanoidRootPart then
	local playerPosition = humanoidRootPart.Position

	-- Check NPCs in ReplicatedStorage
	local replicatedNpcFolder = replicatedStorage.NPCsStorage
	if replicatedNpcFolder and replicatedNpcFolder:IsA("Folder") then
		local npcFolders = replicatedNpcFolder:GetChildren()
		for _, npcFolder in ipairs(npcFolders) do
			if npcFolder:IsA("Folder") then
				local npcPosition = npcFolder.PlayerDetector and npcFolder.PlayerDetector.Position

				if npcPosition then
					local distance = getDistance(playerPosition, npcPosition)

					if distance < distanceThreshold then

						moveNPCToOriginalFolder(npcFolder)

					else

					end
				end
			end
		end
	end

	-- Check NPCs in Workspace
	local workspaceNpcFolders = game.Workspace.NPCs:GetChildren()
	for _, npcFolder in ipairs(workspaceNpcFolders) do
		if npcFolder:IsA("Folder") then
			local npcPosition = npcFolder.PlayerDetector and npcFolder.PlayerDetector.Position

			if npcPosition then
				local distance = getDistance(playerPosition, npcPosition)

				if distance > distanceThreshold then
					--wait(10)
					moveNPCToReplicatedStorage(npcFolder)

				else

				end
			end
		end
	end
end

end

local function manageAllPlayers()
for _, player in ipairs(game.Players:GetPlayers()) do
manageNPCsForPlayer(player)
end
end

while true do
manageAllPlayers()
wait(1)
end