So I made an NPC, so when he dies he is supposed to reward the player who killed him 50 cash, but the thing is, how do you find the player?
01 | Target = script.Parent.Value |
02 | Me = script.Parent.Parent |
03 | RS = script.Parent [ "Right Shoulder" ] |
04 | Safe = { "ComputerComplexity" } |
05 | script.Parent.Parent.Humanoid.WalkSpeed = 10 |
06 | function Follow(Part) |
07 | if Part.Parent:FindFirstChild( "Humanoid" ) ~ = nil then |
08 | Target.Value = Part.Parent.Name |
09 | for i = 1 , 20 do |
10 | Me.Humanoid:MoveTo(Part.Parent.Torso.Position, Part.Parent.Torso) |
11 |
12 | wait( 0.025 ) |
13 | end |
14 | end |
15 | end |
The way ROBLOX default weapons and linked leaderboard handle this is inserting a tag (an ObjectValue) into the humanoid they damage, giving its value the player object and whenever any of the humanoids' died event fires it reads the tag's value (if there's one) & awards the player.
However I and probably many others nowadays do it by just checking if the health of a humanoid getting damaged goes under 0 and reward the client which told server to fire a projectile to this direction or something similar.
It's not handled through scripts inside the NPC (until you do it the ROBLOX style, though it also of course requires inserting the tag from seperate script), but rather from the scripts doing the damage.
To add on to OzzyFin's answer:
Inside the script that kills the NPC (from the player):
1 | function onDamage(humanoidYouDamaged) |
2 | local new = Instance.new( "ObjectValue" ,humanoidYouDamaged) |
3 | new.Name = "creator" |
4 | new.Value = thePlayerThisScriptWorksFor |
5 | game.Debris:AddItem(new, 1 ) -- deletes this object after 1 second |
6 | end |
7 |
8 | -- fire this function whenever you damage an NPC, 'onDamage(humanoidObject)' |
Add this code on Line 16
of your script:
01 | local human = Me.Humanoid |
02 | local statName = "Cash" -- name of the stat |
03 |
04 | human.Died:connect( function () |
05 | local tag = human:FindFirstChild( "creator" ) |
06 | if tag then |
07 | local stats = tag.Value:FindFirstChild( "leaderstats" ) |
08 | if stats and pcall (stats [ "StatName" ] .Value = stats [ "StatName" ] .Value) = = true then |
09 | stats [ "StatName" ] .Value = stats [ "StatName" ] .Value + 50 |
10 | end |
11 | end |
12 | end ) |
The pcall
basically checks to see if StatName
exists. The Died
event is when a humanoid dies, and the rest I believe you understand.
Hope I helped :)
~TDP