I require a system that spawns in npcs when a player touches a part. I have three problems:
The npcs can also touch the part and activate it. I want it so only the player can spawn these.
LAG! Cloning the npcs from lighting, I get large amounts of lag!
If the player touches the part again, more will spawn! I want it so you can only spawn npcs once per life. (If you die and come back you can spawn them again.)
I am not the best scripter, so what I have already tried doesn’t work. Help?
Let’s start off with the “once per life” thingy you mentioned.
I suggest having a Server Script to handle whenever a player joins and their character gets spawned.
The reason for that is to have a PlayerAdded Event, detecting when a player joins. It would create a Value, preferably a BoolValue that can be used to check if the player has actually used the spawing thing you mentioned. The value would then be reset ( .Value = false ) whenever the player’s character spawns, meaning they have died/reset and needed their value to return to false.
You will need to add a check for if the Player’s BoolValue is set to false (not spawned anything yet) in your spawining script, of course.
Now, for the part where you touch the part.
You could add a check in your code, detecting if the part that touched your Part (where you use to spawn npcs) belongs to a Player’s Character, by doing game.Players:GetPlayerFromCharacter(hit.Parent)
(hit is the part that has touched your Part)
Then you will be able to run the rest of the code when the script checks that this is not a NPC.
Finally, I suggest adding the NPCs you want to clone in ServerStorage. I’ve never had any trouble cloning stuff from there.
local Players = game:GetService("Players")
local NPC = game:GetService("Lighting").NPC
local Part = workspace.Part
local Used = {}
Part.Touched:Connect(function(hit)
local Player = Players:GetPlayerFromCharacter(hit.Parent)
if Player then
if not table.find(Used, Player) then
table.insert(Used, Player)
NPC:Clone().Parent = workspace
end
end
end)
Players.PlayerAdded:Connect(function(Player)
Player.CharacterAdded:Connect(function(Character)
if table.find(Used, Player) then
table.remove(Used, table.find(Used,Player))
end
end)
end)
Thank You so much! This is really helpful. What if I wanted to make it so the NPC’s you spawned dies when you die? (If its not too much trouble, you’ve already done so much for me…) (I am making a single player game if that helps simplify things…)
local Players = game:GetService("Players")
local NPC = game:GetService("Lighting").NPC
local Part = workspace.Part
local Used = {}
Part.Touched:Connect(function(hit)
local Player = Players:GetPlayerFromCharacter(hit.Parent)
if Player and Used[Player] == nil then
local Clone = NPC:Clone()
Used[Player] = Clone
Clone.Parent = workspace
end
end)
Players.PlayerAdded:Connect(function(Player)
Player.CharacterAdded:Connect(function(Character)
if Used[Player] ~= nil then
Used[Player]:Destroy()
Used[Player] = nil
end
end)
end)