local rs = game:GetService("ReplicatedStorage") local ss =…
- User
local rs = game:GetService("ReplicatedStorage") local ss = game:GetService("ServerStorage")
local Get = require(rs.Get)
local NPCsConfig = require(Get.SSConfigs.NPCsConfig) local RaritiesConfig = require(Get.SSConfigs.RaritiesConfig) local VariantsConfig = require(Get.SSConfigs.VariantsConfig)
local npcFolder = ss.NPCs local spawnPointsFolder = workspace.Map.SpawnPoints
local lastSpawnTime = os.time() local MIN_DISTANCE = 28
local NPC_SPEED = 12 local NPC_SCALE = 1.3 local COOLDOWN = 3
local npcList = {}
local function GetRarityFromChance(chance) local thresholds = { { name = "Common", min = 10 }, { name = "Uncommon", min = 6 }, { name = "Rare", min = 2.5 }, { name = "Epic", min = 1 }, { name = "Legendary", min = 0.15 }, { name = "Mythic", min = 0.05 }, { name = "Ultimate", min = 0.001 }, }
table.sort(thresholds, function(a, b) return a.min > b.min end) for _, r in ipairs(thresholds) do if chance >= r.min then local config = RaritiesConfig[r.name] if config then return r.name, config.Multiplier end end end return "Common", RaritiesConfig.Common.Multiplierend
local function PickWeightedVariant(variants) local total, weighted = 0, {}
for _, name in ipairs(variants) do local data = VariantsConfig[name] if data then total += data.Chance table.insert(weighted, {name = name, chance = data.Chance, multiplier = data.Multiplier}) end end if total == 0 then return variants[1] end local roll, accum = math.random() * total, 0 for _, v in ipairs(weighted) do accum += v.chance if roll <= accum then return v.name, v.multiplier end end return weighted[1].name, weighted[1].multiplierend
for _, category in pairs(NPCsConfig) do for name, data in pairs(category) do if data.Spawns and data.Chance and data.BaseValue and data.Variants then local rarityName, rarityMultiplier = GetRarityFromChance(data.Chance) local variantName, variantMultiplier = PickWeightedVariant(data.Variants) local combinedChance = data.Chance * rarityMultiplier * variantMultiplier local combinedValue = math.floor(data.BaseValue * variantMultiplier)
table.insert(npcList, { name = name, rarity = rarityName, variant = variantName, chance = combinedChance, value = combinedValue }) end endend
local totalChance = 0
for _, npc in ipairs(npcList) do totalChance += npc.chance end
local lastPickedName = nil local lastPickedCount = 0
local function GetRandomNPC() local tries = 0
while true do tries += 1 local roll, accum = math.random() * totalChance, 0 local chosenNPC = nil for _, npc in ipairs(npcList) do accum += npc.chance if roll <= accum then chosenNPC = npc break end end if not chosenNPC then chosenNPC = npcList[#npcList] end if chosenNPC.name == lastPickedName then if lastPickedCount < 2 then lastPickedCount += 1 return chosenNPC else if tries >= 10 then lastPickedCount = 1 return chosenNPC end end else lastPickedName = chosenNPC.name lastPickedCount = 1 return chosenNPC end endend
local function Walk(npc, spawnCFrame) local hrp = npc:FindFirstChild("HumanoidRootPart") local humanoid = npc:FindFirstChildOfClass("Humanoid")
if not (hrp and humanoid) then return end local targetPosition = spawnCFrame.Position + (spawnCFrame.LookVector * 475) task.spawn(function() while npc and npc.Parent do humanoid:MoveTo(targetPosition) local reached = humanoid.MoveToFinished:Wait() if reached then if npc and npc.Parent then npc:Destroy() end break end end end)end
local function SetNetworkOwnership(npc) local hrp = npc:FindFirstChild("HumanoidRootPart") if not hrp then return end
local closestPlayer, closestDist = nil, math.huge for _, player in pairs(game.Players:GetPlayers()) do local char = player.Character if char and char:FindFirstChild("HumanoidRootPart") then local dist = (char.HumanoidRootPart.Position - hrp.Position).Magnitude if dist < closestDist then closestPlayer = player closestDist = dist end end end if closestPlayer then hrp:SetNetworkOwner(closestPlayer) endend
local function SpawnNPCAt(spawnCFrame) for _, existingNPC in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not existingNPC:HasTag("NPC") then continue end local hrp = existingNPC:FindFirstChild("HumanoidRootPart") if hrp and (hrp.Position - spawnCFrame.Position).Magnitude < MIN_DISTANCE then return end end
for _ = 1, 10 do local picked = GetRandomNPC() local model = npcFolder:FindFirstChild(picked.name) if model and model:IsA("Model") and model.PrimaryPart then local npc = model:Clone() local torso = npc:WaitForChild("Torso") local hum = npc:FindFirstChildOfClass("Humanoid") local animateClone = script.Animate:Clone() animateClone.Parent = npc animateClone.Enabled = true local highlightClone = script.Highlight:Clone() highlightClone.Adornee = npc highlightClone.Parent = npc npc:AddTag("NPC") npc:SetPrimaryPartCFrame(spawnCFrame) npc:SetAttribute("Walking", true) npc:ScaleTo(NPC_SCALE) torso.Neck.C0 = CFrame.new(Vector3.new(0, NPC_SCALE, 0)) * CFrame.Angles(0,0,0) torso.Neck.C1 = CFrame.new(Vector3.new(0, -0.5 * NPC_SCALE, 0)) * CFrame.Angles(0,0,0) npc.Parent = workspace.Map.NPCs.Roaming SetNetworkOwnership(npc) model.PrimaryPart.Anchored = true task.delay(0.1, function() for _, v in pairs(npc:GetDescendants()) do if v:IsA("BasePart") then v.CollisionGroup = "Non-Collidable" v.Anchored = false v.CanCollide = false v.CanQuery = false v.CanTouch = false v.AudioCanCollide = false v.EnableFluidForces = false v.Massless = true end end hum.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None hum.DisplayName = "" hum.HealthDisplayDistance = 0 hum.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff hum.NameOcclusion = Enum.NameOcclusion.NoOcclusion hum.BreakJointsOnDeath = false hum.EvaluateStateMachine = true hum.RequiresNeck = true hum.AutoRotate = false hum.AutomaticScalingEnabled = true hum.MaxHealth = math.huge hum.Health = math.huge hum.MaxSlopeAngle = 0 hum.AutoJumpEnabled = false hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") hum.UseJumpPower = false hum.JumpHeight = 0 end) task.delay(0.1, Walk, npc, spawnCFrame) print(string.format("Spawned: %s | Rarity: %s | Variant: %s | Value: %d", picked.name, picked.rarity, picked.variant, picked.value)) return end endend
local function InitializeSpawn() while Get.SS:GetAttribute("ShouldSpawn") do task.wait()
if os.time() - lastSpawnTime >= COOLDOWN then lastSpawnTime = os.time() for _, point in pairs(spawnPointsFolder:GetChildren()) do if point:IsA("BasePart") then task.spawn(SpawnNPCAt, point.CFrame) end end end endend
Get.SS:GetAttributeChangedSignal("SpeedMultiplier"):Connect(function() for i, npc in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not npc:HasTag("NPC") then continue end
local hum = npc:FindFirstChildOfClass("Humanoid") hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") endend)
task.spawn(InitializeSpawn)
fix the network ownership and issues with spawning, managing distance between npcs before spawning
Assistant
Looking at your code, I can see several issues with network ownership and spawn distance management. Here's a fixed version with improvements:
local rs = game:GetService("ReplicatedStorage") local ss = game:GetService("ServerStorage") local RunService = game:GetService("RunService") local Get = require(rs.Get) local NPCsConfig = require(Get.SSConfigs.NPCsConfig) local RaritiesConfig = require(Get.SSConfigs.RaritiesConfig) local VariantsConfig = require(Get.SSConfigs.VariantsConfig) local npcFolder = ss.NPCs local spawnPointsFolder = workspace.Map.SpawnPoints local lastSpawnTime = os.time() local MIN_DISTANCE = 28 local NPC_SPEED = 12 local NPC_SCALE = 1.3 local COOLDOWN = 3 local npcList = {} local pendingSpawns = {} -- Track spawn points currently spawning NPCs local function GetRarityFromChance(chance) local thresholds = { { name = "Common", min = 10 }, { name = "Uncommon", min = 6 }, { name = "Rare", min = 2.5 }, { name = "Epic", min = 1 }, { name = "Legendary", min = 0.15 }, { name = "Mythic", min = 0.05 }, { name = "Ultimate", min = 0.001 }, } table.sort(thresholds, function(a, b) return a.min > b.min end) for _, r in ipairs(thresholds) do if chance >= r.min then local config = RaritiesConfig[r.name] if config then return r.name, config.Multiplier end end end return "Common", RaritiesConfig.Common.Multiplier end local function PickWeightedVariant(variants) local total, weighted = 0, {} for _, name in ipairs(variants) do local data = VariantsConfig[name] if data then total += data.Chance table.insert(weighted, {name = name, chance = data.Chance, multiplier = data.Multiplier}) end end if total == 0 then return variants[1] end local roll, accum = math.random() * total, 0 for _, v in ipairs(weighted) do accum += v.chance if roll <= accum then return v.name, v.multiplier end end return weighted[1].name, weighted[1].multiplier end for _, category in pairs(NPCsConfig) do for name, data in pairs(category) do if data.Spawns and data.Chance and data.BaseValue and data.Variants then local rarityName, rarityMultiplier = GetRarityFromChance(data.Chance) local variantName, variantMultiplier = PickWeightedVariant(data.Variants) local combinedChance = data.Chance * rarityMultiplier * variantMultiplier local combinedValue = math.floor(data.BaseValue * variantMultiplier) table.insert(npcList, { name = name, rarity = rarityName, variant = variantName, chance = combinedChance, value = combinedValue }) end end end local totalChance = 0 for _, npc in ipairs(npcList) do totalChance += npc.chance end local lastPickedName = nil local lastPickedCount = 0 local function GetRandomNPC() local tries = 0 while true do tries += 1 local roll, accum = math.random() * totalChance, 0 local chosenNPC = nil for _, npc in ipairs(npcList) do accum += npc.chance if roll <= accum then chosenNPC = npc break end end if not chosenNPC then chosenNPC = npcList[#npcList] end if chosenNPC.name == lastPickedName then if lastPickedCount < 2 then lastPickedCount += 1 return chosenNPC else if tries >= 10 then lastPickedCount = 1 return chosenNPC end end else lastPickedName = chosenNPC.name lastPickedCount = 1 return chosenNPC end end end local function Walk(npc, spawnCFrame) local hrp = npc:FindFirstChild("HumanoidRootPart") local humanoid = npc:FindFirstChildOfClass("Humanoid") if not (hrp and humanoid) then return end local targetPosition = spawnCFrame.Position + (spawnCFrame.LookVector * 475) task.spawn(function() while npc and npc.Parent do humanoid:MoveTo(targetPosition) local reached = humanoid.MoveToFinished:Wait() if reached then if npc and npc.Parent then npc:Destroy() end break end end end) end local function SetNetworkOwnership(npc) -- Wait a frame to ensure physics are properly initialized RunService.Heartbeat:Wait() local hrp = npc:FindFirstChild("HumanoidRootPart") if not hrp then return end -- Try to set network ownership with error handling local success, err = pcall(function() local closestPlayer, closestDist = nil, math.huge for _, player in pairs(game.Players:GetPlayers()) do local char = player.Character if char and char:FindFirstChild("HumanoidRootPart") then local dist = (char.HumanoidRootPart.Position - hrp.Position).Magnitude if dist < closestDist then closestPlayer = player closestDist = dist end end end if closestPlayer then hrp:SetNetworkOwner(closestPlayer) else -- If no players, set to server hrp:SetNetworkOwner(nil) end end) if not success then warn("Failed to set network ownership:", err) end end local function CanSpawnAt(spawnPosition) -- Check existing NPCs for _, existingNPC in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not existingNPC:HasTag("NPC") then continue end local hrp = existingNPC:FindFirstChild("HumanoidRootPart") if hrp and (hrp.Position - spawnPosition).Magnitude < MIN_DISTANCE then return false end end -- Check pending spawns for pendingPos, _ in pairs(pendingSpawns) do if (pendingPos - spawnPosition).Magnitude < MIN_DISTANCE then return false end end return true end local function SpawnNPCAt(spawnCFrame) local spawnPosition = spawnCFrame.Position -- Check if we can spawn here if not CanSpawnAt(spawnPosition) then return end -- Mark this position as pending pendingSpawns[spawnPosition] = true for _ = 1, 10 do local picked = GetRandomNPC() local model = npcFolder:FindFirstChild(picked.name) if model and model:IsA("Model") and model.PrimaryPart then local npc = model:Clone() -- Ensure parts are anchored during setup for _, part in pairs(npc:GetDescendants()) do if part:IsA("BasePart") then part.Anchored = true end end local torso = npc:WaitForChild("Torso") local hum = npc:FindFirstChildOfClass("Humanoid") local animateClone = script.Animate:Clone() animateClone.Parent = npc animateClone.Enabled = true local highlightClone = script.Highlight:Clone() highlightClone.Adornee = npc highlightClone.Parent = npc npc:AddTag("NPC") -- Store spawn data as attributes npc:SetAttribute("Rarity", picked.rarity) npc:SetAttribute("Variant", picked.variant) npc:SetAttribute("Value", picked.value) npc:SetAttribute("Walking", true) -- Position and scale npc:SetPrimaryPartCFrame(spawnCFrame) npc:ScaleTo(NPC_SCALE) torso.Neck.C0 = CFrame.new(Vector3.new(0, NPC_SCALE, 0)) * CFrame.Angles(0,0,0) torso.Neck.C1 = CFrame.new(Vector3.new(0, -0.5 * NPC_SCALE, 0)) * CFrame.Angles(0,0,0) -- Configure humanoid before parenting hum.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None hum.DisplayName = "" hum.HealthDisplayDistance = 0 hum.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff hum.NameOcclusion = Enum.NameOcclusion.NoOcclusion hum.BreakJointsOnDeath = false hum.EvaluateStateMachine = true hum.RequiresNeck = true hum.AutoRotate = false hum.AutomaticScalingEnabled = true hum.MaxHealth = math.huge hum.Health = math.huge hum.MaxSlopeAngle = 0 hum.AutoJumpEnabled = false hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") hum.UseJumpPower = false hum.JumpHeight = 0 -- Parent to workspace npc.Parent = workspace.Map.NPCs.Roaming -- Configure physics properties and unanchor task.defer(function() for _, v in pairs(npc:GetDescendants()) do if v:IsA("BasePart") then v.CollisionGroup = "Non-Collidable" v.CanCollide = false v.CanQuery = false v.CanTouch = false v.AudioCanCollide = false v.EnableFluidForces = false v.Massless = true v.Anchored = false -- Unanchor after all properties are set end end -- Set network ownership after physics are configured SetNetworkOwnership(npc) -- Start walking after everything is set up Walk(npc, spawnCFrame) end) -- Remove from pending spawns pendingSpawns[spawnPosition] = nil print(string.format("Spawned: %s | Rarity: %s | Variant: %s | Value: %d", picked.name, picked.rarity, picked.variant, picked.value)) return end end -- If we failed to spawn, remove from pending pendingSpawns[spawnPosition] = nil end local function InitializeSpawn() while Get.SS:GetAttribute("ShouldSpawn") do task.wait() if os.time() - lastSpawnTime >= COOLDOWN then lastSpawnTime = os.time() -- Spawn NPCs with slight delays to avoid race conditions local spawnPoints = spawnPointsFolder:GetChildren() for i, point in pairs(spawnPoints) do if point:IsA("BasePart") then task.spawn(function() -- Add small random delay to prevent simultaneous spawning task.wait(i * 0.1) SpawnNPCAt(point.CFrame) end) end end end end end Get.SS:GetAttributeChangedSignal("SpeedMultiplier"):Connect(function() for i, npc in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not npc:HasTag("NPC") then continue end local hum = npc:FindFirstChildOfClass("Humanoid") if hum then hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") end end end) task.spawn(InitializeSpawn)Key improvements:
-
Network Ownership: Now properly waits for physics initialization and handles errors. Sets ownership to server if no players are available.
-
Spawn Distance Management: Added a
pendingSpawnstable to track positions where NPCs are currently being spawned, preventing overlapping spawns. -
Proper Anchoring: Parts are anchored during setup and unanchored after all properties are configured, preventing physics glitches.
-
Sequential Setup: Uses
task.deferto ensure all properties are set before starting movement and network ownership assignment. -
Staggered Spawning: Added small delays between spawn points to prevent race conditions.
-
Better Error Handling: Network ownership is wrapped in pcall to handle potential errors gracefully.
-
Attribute Storage: Stores NPC data as attributes for easier access later.
These changes should resolve the network ownership issues and improve spawn distance management significantly.
-
- User
local rs = game:GetService("ReplicatedStorage") local ss = game:GetService("ServerStorage") local RunService = game:GetService("RunService")
local Get = require(rs.Get)
local NPCsConfig = require(Get.SSConfigs.NPCsConfig) local RaritiesConfig = require(Get.SSConfigs.RaritiesConfig) local VariantsConfig = require(Get.SSConfigs.VariantsConfig)
local npcFolder = ss.NPCs local spawnPointsFolder = workspace.Map.SpawnPoints
local lastSpawnTime = os.time() local MIN_DISTANCE = 20
local NPC_SPEED = 12 local NPC_SCALE = 1.3 local COOLDOWN = 3
local npcList = {} local pendingSpawns = {}
local function GetRarityFromChance(chance) local thresholds = { { name = "Common", min = 10 }, { name = "Uncommon", min = 6 }, { name = "Rare", min = 2.5 }, { name = "Epic", min = 1 }, { name = "Legendary", min = 0.15 }, { name = "Mythic", min = 0.05 }, { name = "Ultimate", min = 0.001 }, }
table.sort(thresholds, function(a, b) return a.min > b.min end) for _, r in ipairs(thresholds) do if chance >= r.min then local config = RaritiesConfig[r.name] if config then return r.name, config.Multiplier end end end return "Common", RaritiesConfig.Common.Multiplierend
local function PickWeightedVariant(variants) local total, weighted = 0, {}
for _, name in ipairs(variants) do local data = VariantsConfig[name] if data then total += data.Chance table.insert(weighted, {name = name, chance = data.Chance, multiplier = data.Multiplier}) end end if total == 0 then return variants[1] end local roll, accum = math.random() * total, 0 for _, v in ipairs(weighted) do accum += v.chance if roll <= accum then return v.name, v.multiplier end end return weighted[1].name, weighted[1].multiplierend
for _, category in pairs(NPCsConfig) do for name, data in pairs(category) do if data.Spawns and data.Chance and data.BaseValue and data.Variants then local rarityName, rarityMultiplier = GetRarityFromChance(data.Chance) local variantName, variantMultiplier = PickWeightedVariant(data.Variants) local combinedChance = data.Chance * rarityMultiplier * variantMultiplier local combinedValue = math.floor(data.BaseValue * variantMultiplier)
table.insert(npcList, { name = name, rarity = rarityName, variant = variantName, chance = combinedChance, value = combinedValue }) end endend
local totalChance = 0
for _, npc in ipairs(npcList) do totalChance += npc.chance end
local lastPickedName = nil local lastPickedCount = 0
local function GetRandomNPC() local tries = 0
while true do tries += 1 local roll, accum = math.random() * totalChance, 0 local chosenNPC = nil for _, npc in ipairs(npcList) do accum += npc.chance if roll <= accum then chosenNPC = npc break end end if not chosenNPC then chosenNPC = npcList[#npcList] end if chosenNPC.name == lastPickedName then if lastPickedCount < 2 then lastPickedCount += 1 return chosenNPC else if tries >= 10 then lastPickedCount = 1 return chosenNPC end end else lastPickedName = chosenNPC.name lastPickedCount = 1 return chosenNPC end endend
local function Walk(npc, spawnCFrame) local hrp = npc:FindFirstChild("HumanoidRootPart") local humanoid = npc:FindFirstChildOfClass("Humanoid")
if not (hrp and humanoid) then return end local targetPosition = spawnCFrame.Position + (spawnCFrame.LookVector * 475) task.spawn(function() while npc and npc.Parent do humanoid:MoveTo(targetPosition) local reached = humanoid.MoveToFinished:Wait() if reached then if npc and npc.Parent then npc:Destroy() end break end end end)end
local function SetNetworkOwnership(npc) RunService.Heartbeat:Wait()
local hrp = npc:FindFirstChild("HumanoidRootPart") if not hrp then return end local success, err = pcall(function() local closestPlayer, closestDist = nil, math.huge for _, player in pairs(game.Players:GetPlayers()) do local char = player.Character if char and char:FindFirstChild("HumanoidRootPart") then local dist = (char.HumanoidRootPart.Position - hrp.Position).Magnitude if dist < closestDist then closestPlayer = player closestDist = dist end end end if closestPlayer then hrp:SetNetworkOwner(closestPlayer) else hrp:SetNetworkOwner(nil) end end) if not success then warn("Failed to set network ownership:", err) endend
local function CanSpawnAt(spawnPosition) for _, existingNPC in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not existingNPC:HasTag("NPC") then continue end local hrp = existingNPC:FindFirstChild("HumanoidRootPart") if hrp and (hrp.Position - spawnPosition).Magnitude < MIN_DISTANCE then return false end end
for pendingPos, _ in pairs(pendingSpawns) do if (pendingPos - spawnPosition).Magnitude < MIN_DISTANCE then return false end end return trueend
local function SpawnNPCAt(spawnCFrame) local spawnPosition = spawnCFrame.Position
if not CanSpawnAt(spawnPosition) then return end pendingSpawns[spawnPosition] = true for _ = 1, 10 do local picked = GetRandomNPC() local model = npcFolder:FindFirstChild(picked.name) if model and model:IsA("Model") and model.PrimaryPart then local npc = model:Clone() for _, part in pairs(npc:GetDescendants()) do if part:IsA("BasePart") then part.Anchored = true end end local torso = npc:WaitForChild("Torso") local hum = npc:FindFirstChildOfClass("Humanoid") local animateClone = script.Animate:Clone() animateClone.Parent = npc animateClone.Enabled = true local highlightClone = script.Highlight:Clone() highlightClone.Adornee = npc highlightClone.Parent = npc npc:AddTag("NPC") npc:SetAttribute("Rarity", picked.rarity) npc:SetAttribute("Variant", picked.variant) npc:SetAttribute("Value", picked.value) npc:SetAttribute("Walking", true) npc:SetPrimaryPartCFrame(spawnCFrame) npc:ScaleTo(NPC_SCALE) torso.Neck.C0 = CFrame.new(Vector3.new(0, NPC_SCALE, 0)) * CFrame.Angles(0,0,0) torso.Neck.C1 = CFrame.new(Vector3.new(0, -0.5 * NPC_SCALE, 0)) * CFrame.Angles(0,0,0) hum.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None hum.DisplayName = "" hum.HealthDisplayDistance = 0 hum.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff hum.NameOcclusion = Enum.NameOcclusion.NoOcclusion hum.BreakJointsOnDeath = false hum.EvaluateStateMachine = true hum.RequiresNeck = true hum.AutoRotate = false hum.AutomaticScalingEnabled = true hum.MaxHealth = math.huge hum.Health = math.huge hum.MaxSlopeAngle = 0 hum.AutoJumpEnabled = false hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") hum.UseJumpPower = false hum.JumpHeight = 0 npc.Parent = workspace.Map.NPCs.Roaming task.defer(function() for _, v in pairs(npc:GetDescendants()) do if v:IsA("BasePart") then v.CollisionGroup = "Non-Collidable" v.CanCollide = false v.CanQuery = false v.CanTouch = false v.AudioCanCollide = false v.EnableFluidForces = false v.Massless = true v.Anchored = false end end SetNetworkOwnership(npc) Walk(npc, spawnCFrame) end) pendingSpawns[spawnPosition] = nil print(string.format("Spawned: %s | Rarity: %s | Variant: %s | Value: %d", picked.name, picked.rarity, picked.variant, picked.value)) return end end pendingSpawns[spawnPosition] = nilend
local function InitializeSpawn() while Get.SS:GetAttribute("ShouldSpawn") do task.wait()
if os.time() - lastSpawnTime >= COOLDOWN then lastSpawnTime = os.time() local spawnPoints = spawnPointsFolder:GetChildren() for i, point in pairs(spawnPoints) do if point:IsA("BasePart") then task.spawn(function() task.wait(i * 0.1) SpawnNPCAt(point.CFrame) end) end end end endend
Get.SS:GetAttributeChangedSignal("SpeedMultiplier"):Connect(function() for i, npc in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not npc:HasTag("NPC") then continue end
local hum = npc:FindFirstChildOfClass("Humanoid") if hum then hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") end endend)
task.spawn(InitializeSpawn)
when the client is out of focus on the game while having network ownership, it stops spawning untl they refocus
Assistant
This is a common issue when clients have network ownership and tab out. When a player loses focus on the game, their client stops simulating physics for parts they own, causing NPCs to freeze. Here's a fixed version that addresses this:
local rs = game:GetService("ReplicatedStorage") local ss = game:GetService("ServerStorage") local RunService = game:GetService("RunService") local Get = require(rs.Get) local NPCsConfig = require(Get.SSConfigs.NPCsConfig) local RaritiesConfig = require(Get.SSConfigs.RaritiesConfig) local VariantsConfig = require(Get.SSConfigs.VariantsConfig) local npcFolder = ss.NPCs local spawnPointsFolder = workspace.Map.SpawnPoints local lastSpawnTime = os.time() local MIN_DISTANCE = 20 local NPC_SPEED = 12 local NPC_SCALE = 1.3 local COOLDOWN = 3 local npcList = {} local pendingSpawns = {} local activeNPCs = {} -- Track active NPCs and their last positions -- Configuration for ownership management local OWNERSHIP_CHECK_INTERVAL = 5 -- Check ownership every 5 seconds local STUCK_THRESHOLD = 5 -- Distance threshold to consider NPC stuck local MAX_LIFETIME = 120 -- Maximum lifetime for an NPC in seconds local function GetRarityFromChance(chance) local thresholds = { { name = "Common", min = 10 }, { name = "Uncommon", min = 6 }, { name = "Rare", min = 2.5 }, { name = "Epic", min = 1 }, { name = "Legendary", min = 0.15 }, { name = "Mythic", min = 0.05 }, { name = "Ultimate", min = 0.001 }, } table.sort(thresholds, function(a, b) return a.min > b.min end) for _, r in ipairs(thresholds) do if chance >= r.min then local config = RaritiesConfig[r.name] if config then return r.name, config.Multiplier end end end return "Common", RaritiesConfig.Common.Multiplier end local function PickWeightedVariant(variants) local total, weighted = 0, {} for _, name in ipairs(variants) do local data = VariantsConfig[name] if data then total += data.Chance table.insert(weighted, {name = name, chance = data.Chance, multiplier = data.Multiplier}) end end if total == 0 then return variants[1] end local roll, accum = math.random() * total, 0 for _, v in ipairs(weighted) do accum += v.chance if roll <= accum then return v.name, v.multiplier end end return weighted[1].name, weighted[1].multiplier end for _, category in pairs(NPCsConfig) do for name, data in pairs(category) do if data.Spawns and data.Chance and data.BaseValue and data.Variants then local rarityName, rarityMultiplier = GetRarityFromChance(data.Chance) local variantName, variantMultiplier = PickWeightedVariant(data.Variants) local combinedChance = data.Chance * rarityMultiplier * variantMultiplier local combinedValue = math.floor(data.BaseValue * variantMultiplier) table.insert(npcList, { name = name, rarity = rarityName, variant = variantName, chance = combinedChance, value = combinedValue }) end end end local totalChance = 0 for _, npc in ipairs(npcList) do totalChance += npc.chance end local lastPickedName = nil local lastPickedCount = 0 local function GetRandomNPC() local tries = 0 while true do tries += 1 local roll, accum = math.random() * totalChance, 0 local chosenNPC = nil for _, npc in ipairs(npcList) do accum += npc.chance if roll <= accum then chosenNPC = npc break end end if not chosenNPC then chosenNPC = npcList[#npcList] end if chosenNPC.name == lastPickedName then if lastPickedCount < 2 then lastPickedCount += 1 return chosenNPC else if tries >= 10 then lastPickedCount = 1 return chosenNPC end end else lastPickedName = chosenNPC.name lastPickedCount = 1 return chosenNPC end end end local function Walk(npc, spawnCFrame) local hrp = npc:FindFirstChild("HumanoidRootPart") local humanoid = npc:FindFirstChildOfClass("Humanoid") if not (hrp and humanoid) then return end local targetPosition = spawnCFrame.Position + (spawnCFrame.LookVector * 475) task.spawn(function() while npc and npc.Parent do humanoid:MoveTo(targetPosition) local reached = humanoid.MoveToFinished:Wait() if reached then if npc and npc.Parent then activeNPCs[npc] = nil npc:Destroy() end break end end end) end local function SetNetworkOwnership(npc) RunService.Heartbeat:Wait() local hrp = npc:FindFirstChild("HumanoidRootPart") if not hrp then return end -- Always set ownership to server to avoid client focus issues local success, err = pcall(function() hrp:SetNetworkOwner(nil) -- nil = server ownership end) if not success then warn("Failed to set network ownership:", err) end end local function CheckAndFixStuckNPCs() for npc, data in pairs(activeNPCs) do if npc and npc.Parent then local hrp = npc:FindFirstChild("HumanoidRootPart") if hrp then local currentPos = hrp.Position local timeSinceSpawn = tick() - data.spawnTime -- Check if NPC has exceeded max lifetime if timeSinceSpawn > MAX_LIFETIME then activeNPCs[npc] = nil npc:Destroy() continue end -- Check if NPC is stuck (hasn't moved much) if data.lastPosition then local distanceMoved = (currentPos - data.lastPosition).Magnitude if distanceMoved < STUCK_THRESHOLD then data.stuckTime = (data.stuckTime or 0) + OWNERSHIP_CHECK_INTERVAL -- If stuck for too long, reset ownership or destroy if data.stuckTime > 15 then -- Try to reset ownership to server SetNetworkOwnership(npc) -- If still stuck after multiple attempts, destroy if data.stuckTime > 30 then activeNPCs[npc] = nil npc:Destroy() end end else data.stuckTime = 0 end end data.lastPosition = currentPos end else -- Clean up invalid references activeNPCs[npc] = nil end end end local function CanSpawnAt(spawnPosition) for _, existingNPC in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not existingNPC:HasTag("NPC") then continue end local hrp = existingNPC:FindFirstChild("HumanoidRootPart") if hrp and (hrp.Position - spawnPosition).Magnitude < MIN_DISTANCE then return false end end for pendingPos, _ in pairs(pendingSpawns) do if (pendingPos - spawnPosition).Magnitude < MIN_DISTANCE then return false end end return true end local function SpawnNPCAt(spawnCFrame) local spawnPosition = spawnCFrame.Position if not CanSpawnAt(spawnPosition) then return end pendingSpawns[spawnPosition] = true for _ = 1, 10 do local picked = GetRandomNPC() local model = npcFolder:FindFirstChild(picked.name) if model and model:IsA("Model") and model.PrimaryPart then local npc = model:Clone() for _, part in pairs(npc:GetDescendants()) do if part:IsA("BasePart") then part.Anchored = true end end local torso = npc:WaitForChild("Torso") local hum = npc:FindFirstChildOfClass("Humanoid") local animateClone = script.Animate:Clone() animateClone.Parent = npc animateClone.Enabled = true local highlightClone = script.Highlight:Clone() highlightClone.Adornee = npc highlightClone.Parent = npc npc:AddTag("NPC") npc:SetAttribute("Rarity", picked.rarity) npc:SetAttribute("Variant", picked.variant) npc:SetAttribute("Value", picked.value) npc:SetAttribute("Walking", true) npc:SetPrimaryPartCFrame(spawnCFrame) npc:ScaleTo(NPC_SCALE) torso.Neck.C0 = CFrame.new(Vector3.new(0, NPC_SCALE, 0)) * CFrame.Angles(0,0,0) torso.Neck.C1 = CFrame.new(Vector3.new(0, -0.5 * NPC_SCALE, 0)) * CFrame.Angles(0,0,0) hum.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None hum.DisplayName = "" hum.HealthDisplayDistance = 0 hum.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff hum.NameOcclusion = Enum.NameOcclusion.NoOcclusion hum.BreakJointsOnDeath = false hum.EvaluateStateMachine = true hum.RequiresNeck = true hum.AutoRotate = false hum.AutomaticScalingEnabled = true hum.MaxHealth = math.huge hum.Health = math.huge hum.MaxSlopeAngle = 0 hum.AutoJumpEnabled = false hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") hum.UseJumpPower = false hum.JumpHeight = 0 npc.Parent = workspace.Map.NPCs.Roaming -- Track this NPC activeNPCs[npc] = { spawnTime = tick(), lastPosition = spawnCFrame.Position, stuckTime = 0 } task.defer(function() for _, v in pairs(npc:GetDescendants()) do if v:IsA("BasePart") then v.CollisionGroup = "Non-Collidable" v.CanCollide = false v.CanQuery = false v.CanTouch = false v.AudioCanCollide = false v.EnableFluidForces = false v.Massless = true v.Anchored = false end end SetNetworkOwnership(npc) Walk(npc, spawnCFrame) end) pendingSpawns[spawnPosition] = nil print(string.format("Spawned: %s | Rarity: %s | Variant: %s | Value: %d", picked.name, picked.rarity, picked.variant, picked.value)) return end end pendingSpawns[spawnPosition] = nil end local function InitializeSpawn() -- Start the ownership check loop task.spawn(function() while true do task.wait(OWNERSHIP_CHECK_INTERVAL) CheckAndFixStuckNPCs() end end) -- Main spawn loop while Get.SS:GetAttribute("ShouldSpawn") do task.wait() if os.time() - lastSpawnTime >= COOLDOWN then lastSpawnTime = os.time() local spawnPoints = spawnPointsFolder:GetChildren() for i, point in pairs(spawnPoints) do if point:IsA("BasePart") then task.spawn(function() task.wait(i * 0.1) SpawnNPCAt(point.CFrame) end) end end end end end Get.SS:GetAttributeChangedSignal("SpeedMultiplier"):Connect(function() for i, npc in pairs(workspace.Map.NPCs.Roaming:GetChildren()) do if not npc:HasTag("NPC") then continue end local hum = npc:FindFirstChildOfClass("Humanoid") if hum then hum.WalkSpeed = NPC_SPEED * Get.SS:GetAttribute("SpeedMultiplier") end end end) task.spawn(InitializeSpawn)Key changes to fix the focus issue:
-
Server Ownership: NPCs now always have server ownership (
SetNetworkOwner(nil)), preventing client focus issues entirely. -
NPC Tracking: Added an
activeNPCstable to monitor all spawned NPCs and detect if they're stuck. -
Stuck Detection: Implements a system that checks if NPCs haven't moved significantly every few seconds and handles them appropriately.
-
Lifetime Limits: NPCs have a maximum lifetime to prevent accumulation of stuck entities.
-
Automatic Cleanup: Stuck or expired NPCs are automatically removed, ensuring the spawn system continues working.
This approach eliminates the client focus problem by keeping physics simulation on the server, which never loses focus.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.