I’d like to detect when the player kills an npc and what the name of the npc was by firing a remote event called “KillEnemy” so I can award the player XP, but whenever I try for some reason studio doesn’t pick up when the player kills an npc.
What i’ve tried:
StarterCharacterScript
human.Died:Connect(function()
local player = game.Players:GetPlayerFromCharacter(char)
if player then
game.ReplicatedStorage:WaitForChild("KillEnemy"):FireClient(player)
end
end)
local ss = game:GetService("ServerStorage")
local characterBarGui = ss.CharacterBar
local char = script.Parent
local human = char:WaitForChild("Humanoid")
local characterBarClone = characterBarGui:Clone()
characterBarClone.Parent = char
characterBarClone.Adornee = char:WaitForChild("Head")
human.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
human.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff
characterBarClone.MainHealth.healthChnged.Disabled = false
human.Died:Connect(function()
local player = game.Players:GetPlayerFromCharacter()
game.ReplicatedStorage:WaitForChild("KillEnemy"):FireServer(player)
end)
For this to work on an npc, the simplest way to do it is to move this into a script in the npc (this will cause performance issues with many npcs, use module scripts for this).
local attacker = nil -- set this when a player hits the npc
human.Died:Connect(function()
local player = game.Players:GetPlayerFromCharacter(attacker)
if player then
-- award player
end
end)
The problem you’re facing right now is that you have no way of identifying what player killed the NPC. Possible solutions would be:
Adjust the weapon script / damage system, such that it adds a tag with the weapon users name (or other identifier) in the character model of the NPC. Upon death, check for this tag to see who killed the NPC.
Caveat: If multiple users damage an NPC, you’ll have to determine a system to figure out who should get the XP for actually killing it, since just checking for a tag may give XP to a player who only did 1 point of damage and not to the user who did 99 points of damage.
After damaging the NPC with the weapon, check its health and if its 0, fire the remote and pass the weapon’s user as the character/player who killed the NPC (this would also be done in the weapon script)