I want to make a NPC respawn every time it goes outside of a zone in region3. But the problem is that when I step into the region, the npc just start resetting until i step outside of the region. But the npc doesnt reset when It steps outside of the region?
also here’s my code I have so far.
local part1 = workspace.Part
local Part2 = workspace.Part2
local region = Region3.new(part1.Position,Part2.Position)
local p = Instance.new("Part",workspace)
p.Size = region.Size
p.CFrame = region.CFrame
p.Transparency = 0.5
p.Material = "ForceField"
p.CanCollide = false
p.Anchored = true
local ignorelist = {part1,Part2,p}
local npcinregion = {}
while wait(0.1) do
local regionparts = workspace:FindPartsInRegion3WithIgnoreList(region,ignorelist,math.huge)
for i,v in pairs(regionparts) do
if v.Parent:FindFirstChild("Humanoid") then
local name = v.Parent.Name
table.insert(npcinregion,name)
if not table.find(npcinregion,game.Workspace.Ghost.Name) then
game.Workspace.Ghost:SetPrimaryPartCFrame(game.Workspace.help.CFrame)
end
end
end
table.clear(npcinregion)
end
if anyone has any idea what im doing wrong, please tell me.
Thanks in advance!
Haven’t thoroughly read through it, but I did notice that you’re not accounting for the player’s character stepping into/out of the region. Your script thinks that YOU are also an NPC, this could be causing it to not function as intended.
You have two if-statements inside the for-loop. The second if-statement should have been outside the for-loop.
What happens now: You check all the parts in the region. If there are no parts found, nothing happens. If the player is there, and it happens to come first in the list of found parts, it resets the ghost.
You want to check all the parts first, and only after that reset the ghost if it wasn’t found in the region.
–
Additional advice:
Personally I would not have put the names in a table to use table.find(). Instead I would have used a boolean ghostFound = false, and set it to true upon finding the ghost. Then after the loop check the boolean to know if it should be reset. By checking the name already in the for loop, you can also use the ‘break’ keyword to stop looking for more ghosts, there is apparently only 1 after all.
In fact you don’t need to use the name at all, it’s much better to just check the object reference directly. What if a player named Ghost enters your game. This goes as a general rule.
You could also move the for-loop to a function, and return true when you find the ghost and nothing if it wasn’t found.
The indentation of your code makes it a bit confusing, it’s easier to see the problem by stricly observing the correct spacing around the if-statements and for-loops. Good luck!