Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Rewarding Players For Killing NPC's?

Asked by
dyler3 1510 Moderation Voter
10 years ago

So, recently I've been working on creating my own NPC's and all that stuff...well anyways, my question to whoever is willing to help is: How do I find the player who killed the NPC? How would I be able to do this, and find the exact player who killed the NPC so that I can award them? (I want the player to be awarded gold when the NPC is killed.)

Gold Stat: game.Players.Player.leaderstats.Gold

Heres what I have so far in the sword I made:

01Plr=game.Players.LocalPlayer
02Mouse=Plr:GetMouse()
03Swinging=false
04ReadyToSwing=true
05SwingTime=.75
06 
07---Functions---
08function Swing()
09    Swinging=true
10    ReadyToSwing=false
11    script.Parent.Parent.GripForward=Vector3.new(1,0,0)
12    script.Parent.Parent.GripPos=Vector3.new(0,0,-1)
13    script.Parent.Parent.GripRight=Vector3.new(0,1,0)
14    script.Parent.Parent.GripUp=Vector3.new(0,0,0)
15    wait(SwingTime)
View all 41 lines...

If anyone could possibly help me, thank you in advance.

(If any more information is needed, please leave a comment.)

1 answer

Log in to vote
1
Answered by
yumtaste 476 Moderation Voter
10 years ago

The way I do this is by having an ObjectValue called "attacker" with the value of the player be inserted into the NPC's Humanoid. Then, in the NPC, there's an event that listens for .Died(), and it will use the "attacker" ObjectValue to find the player's leaderstats, and then add gold. Maybe a little something like this? (Note: this doesn't have to be a new script. It can be added into the function on line 25)

01--in the object that will damage the NPC upon hitting it
02 
03script.Parent.Touched:connect(function(part)
04if part.Parent:FindFirstChild("Humanoid") then
05local humanoid = part.Parent:FindFirstChild("Humanoid")
06local attacker = Instance.new("ObjectValue", humanoid)
07attacker.Name = "attacker"
08attacker.Value = Plr
09attacker.Parent = humanoid
10Debris:AddItem(attacker, 0.5) --you can change this part, maybe add something to delete everything called "attacker" in humanoid before inserting it, this part just makes it automatically remove itself after 0.5 seconds.
11end
12end
13end)
1--in NPC's Humanoid
2 
3script.Parent.Died:connect(function()
4local attacker = script.Parent:FindFirstChild("attacker")
5if attacker then
6attacker.Value.leaderstats.Gold.Value = attacker.Value.leaderstats.Gold.Value
7end
8end)

If this code doesn't work, or you need more help, leave a comment!

1
Yes, this works :D. Thanks for the response. Thumbs up :P dyler3 1510 — 10y
0
Thanks. More people should ask questions like you do. Your question was very thorough and easy to read, and allowed me to give you an answer quickly and easily. yumtaste 476 — 10y
Ad

Answer this question