Part that spawns npc when touched not working

Screenshot 2023-04-18 183347

So i made a script so that when you touch the part it spawns a npc.But when you touch it it keeps spawning like thousands of npcs when i just want 1 to spawn.

The reason why your script keeps spawning thousands of NPCs is because the while true do loop continuously runs, causing the Touched event to be connected multiple times.

To fix this, you should move the event connection outside of the loop and use a Boolean value to keep track of whether an NPC has already been spawned or not.

I’d also suggest using functions instead of a while true do loop.

local hasTouched = false -- Initialize a boolean variable to false

local function onTouch(part)
    if hasTouched then return end -- If the part has already been touched, exit the function
    
    hasTouched = true -- Set the boolean variable to true to indicate the part has been touched
    print("The part has been touched!")
end

script.Parent.Touched:Connect(onTouch) -- Connect the Touched event to the onTouch function