0

So I am coding a game where on an NPC's death, The player's kills score goes up by 1 but there seems to be an error when I fix it all the time. It's either an 'Attempted to add Instance and Number' or 'Attempt to index number with 'Value'' Here is the code for you below (please note that the script is the NPC's Child.)

--code below --

enemies_killed = game.StarterGui["Enemies Defeated"].Frame.enemydefeatednum.enemies_killed

print(dead_bool)

NPC_died = 0

while true do
    wait(0.1)

    if script.Parent.Humanoid ~= nil then
        if script.Parent.Humanoid.Health <= 0 then
            NPC_died += 1
            dead_bool = true

            enemies_killed  = enemies_killed.Value + 1

            print(enemies_killed)
            wait(0.1)
        end
    end
end
Byte Ninja
  • 881
  • 5
  • 13

1 Answers1

0

Rather than setting this all up, you can use an event to detect when the humanoid dies and adding 1 to the player's killcount.

Based off your own script, that would look something like

script.Parent.Humanoid.Died:Once(function()
    NPC_Died += 1
end)

However, I personally would approach this in a different way:

Instead of having a separate script for each NPC, you could have a script that will use events to detect for all NPCs, including any that may be added to the folder in the future, and count when each one dies and then adds it to the kill count.

local killCount = 0
local npcFolder = .../NPCFolder -- Where ever this is

for i, npc in npcFolder:GetChildren() do
    if npc and npc.Humanoid then
        npc.Humanoid.Died:Once(function()
            NPC_Died += 1
            -- do whatever else you want here, such as removing the NPC after a while using the debris service
        end
    end
end

npcFolder.ChildAdded:Connect(function(child)
    if child:FindFirstChildWhichIsA("Humanoid") then
        -- A new humanoid has been added to the NPC folder
        child.Humanoid.Died:Once(function()
            NPC_Died += 1
        end
    end
end)

(I haven't used RS in a long while sorry if i mistake )

Azimus
  • 32
  • 3
  • Where does this script go? Does it go into a folder and how can I also get who killed the NPC? Thank you. – polarshark123 Jul 25 '23 at 01:42
  • If you were to use the first suggestion, you could just replace the while loop with the first suggestion, which would be for the script that was in each NPCs child. – Azimus Jul 26 '23 at 21:23
  • If you were to use the second suggestion, you would make a folder for the NPCS, place all the NPCS you want inside the folder as direct children, then change the npcFolder variable to the folder itself. If you want to get who killed the NPC, this would be done best by using a tagging system, or more simply, adding a check for each weapon; whenever the weapon deals damage, if it kills the humanoid it deals damage to then you would count that as a kill. However, this is a separate script entirely. – Azimus Jul 26 '23 at 21:25