So I have this script that’s supposed to make an NPC take fall damage. However, whenever it’s run and the function is called, my Roblox Studio, without fail, crashes. I’ve tried it out in the published game, and it works fine there, but I’m not about to publish my game and join it every time I need to playtest.
Here is the offending code:
local posnow = 0
local air = false
enemy.Humanoid:GetPropertyChangedSignal("FloorMaterial"):Connect(function()
if enemy.Humanoid.FloorMaterial == Enum.Material.Air then
posnow = enemy.HumanoidRootPart.Position
air = true
else
if air == true then
air = false
local newpos = enemy.HumanoidRootPart.Position
local ydif = math.abs(posnow.Y - newpos.Y)
local damage = math.round((((5 + enemy.CharacterData:GetAttribute("Weight")) * ydif) - 50) * (1 - (enemy.CharacterData:GetAttribute("FallDamageResistance")/100)))
print(enemy.Name .. " took " .. damage .. " fall damage.")
enemy.CharacterData:SetAttribute("Health", enemy.CharacterData:GetAttribute("Health") - damage)
end
end
end)
This isn’t the entire script, only the part that crashes Studio. I can provide the whole script and related module scripts if necessary.
Okay, so it seems that the function that :Destroy()s the enemy’s model after they die is causing the issue. Here is that code,
local info = enemy.CharacterData
info:GetAttributeChangedSignal("Health"):Connect(function()
if info:GetAttribute("Health") <= 0 then
--[[game.ReplicatedStorage.GameProgress.TotalEnemiesRemaining.Value -= 1
game.ReplicatedStorage.GameProgress.EnemiesKilled.Value += 1
if info.BlockedBy.Value then
local char = info.BlockedBy.Value
for i, v in pairs(char.CharacterData.PeopleBlocking:GetChildren()) do
if v.Value == enemy then
v:Destroy()
end
end
end --]]
-- Commenting these out because they're part of the code but almost certainly not causing the issue.
enemy:Destroy() -- Removing this line fixes the issue.
end
end)
However, this code works perfectly under any other circumstances, and only crashes Studio when an enemy specifically dies of fall damage. And this line of code,
that kills the enemy with fall damage, is no different than another line in a different script that kills the enemy. I’m not sure what else could possibly be causing it.
I’m honestly unsure on where the issue is coming from.
Desperate times call for desperate measures, maybe try printing the amount of damage being applied from the fall damage?
And also print on the health attribute change?