Ok, so I'm making a simulator and I have run into a issue, I need to figure out how to make a weapon that only hurts NPCs so if you can help me please walk me through it it would be much appreciated if you could!
This is very simple. All you have to do is check if the hit model has four major characteristics:
If it has a humanoid, you know your weapon is not hitting a wall.
To start off, we'll make a .Touched:Connect() function.
script.Parent.Touched:Connect(function(Hit) end)
This will allow you to detect if the sword is being touched. The first argument, which I decided to call "Hit," will be the part that touched the sword. Note the parenthesis at the end. We are creating a function inside of the Connect, so we still have to close the connect too.
Next, we will check if the Hit's parent is not nil, and if it has a humanoid.
script.Parent.Touched:Connect(function(Hit) if (Hit) and Hit.Parent and (Hit.Parent:FindFirstChild('Humanoid')) then end end)
Now that we have that done, we can check if the model isn't a player model by using Players:GetPlayerFromCharacter(). This will return a Player object if the first argument provided is valid. We put the "not" keyword before it so we make that the person is an NPC.
script.Parent.Touched:Connect(function(Hit) if (Hit) and Hit.Parent and Hit.Parent:FindFirstChild('Humanoid')) and not game:GetService('Players'):GetPlayerFromCharacter(Hit.Parent) then Hit.Parent.Humanoid:takeDamage(yourdamagevalue_here) end end)
We also need to add a debounce to make sure that the player doesn't do that cool Ocarina of Time glitch.
local Debounce = false; script.Parent.Touched:Connect(function(Hit) if (not Debounce) and (Hit) and Hit.Parent and Hit.Parent:FindFirstChild('Humanoid')) and not game:GetService('Players'):GetPlayerFromCharacter(Hit.Parent) then Debounce = true; Hit.Parent.Humanoid:takeDamage(yourdamagevalue_here) wait(2.5) Debounce = false; end end)
What we do here is make a debounce, but in the if statement, if the "not Debounce" passes, aka if Debounce is false (which the 'not' keyword turns to true and makes the if statement pass), alongside with all the other conditions passing, the if statement will continue. Otherwise, if "Debounce" is true, or if any of the other conditions are false, then the if statement will not pass. We then make Debounce false again after 2.5 seconds to allow the script to run again.
~Fifkee