Can't figure out how to detect if the part has been destroyed

Issues I see within your script.

  1. RBXConnectionEvents, should not be in loops like what you’ve done, they will always run no matter what so there is no use to loop it. If you want to disconnect and connect and certain times, I recommend taking a look at this Forum and Roblox’s Guide

  2. Touched Event, Touch Events are not very accurate, for example, If you were to put something completely still, it wont detect the touched event. So rather use game.Workspace:GetPartsInPart(HIT_BOX)

  3. Your code is un-readable. I cannot understand anything when I read this. Add comments, un-nest your code and Refactor your code; without doing this your code will make you think everything is fine because its bunched up like cables, and unlabeled (bars)

Trying to fix it
Using these issues and some improvements this is what I’ve got.

--[[ 

goal : My script detects if the monster is touched by a part, 
    and then if it does; it freezes the monster as a statue. 
    If the vision part is no longer touching the monster; 
    the monster unfreezes and runs super fast. 

issue : The issue lies when the player vision part touches the monster last second, 
    triggering the monster to freeze, yet is too late and is destroyed by the monster. 
    This causes the monster to be stuck in it’s first stage, being a statue. 

How am I able to detect when this happens (the vision part being destroyed) and cause the monster to run super fast again?

--]]

--// Objects
local HitBox = script.Parent
local Monster = HitBox.Parent
local MonsterHumanoid : Humanoid = Monster.Humanoid

--// Values
local BeingDelayed = false

local TouchingParts = {}

local Filter = OverlapParams.new()
Filter.FilterType = Enum.RaycastFilterType.Exclude
--Filter:AddToFilter(HitBox)

--// Functions
local function SetMonsterWalkSpeed(speed:number)
    MonsterHumanoid.WalkSpeed = speed
end

local function GetTouchingParts(Part:BasePart, Params:OverlapParams) : {string}
    local Touching = game.Workspace:GetPartsInPart(Part, Params)
    local Custom = {}

    for _, Object:BasePart in Touching do
        if Object:IsA('BasePart') then
            table.insert(Custom, Object.Name)
        end
    end

    return Custom
end

local function MonsterFreezed(isFreezed:boolean)
    if BeingDelayed then
        return
    end

    if isFreezed then
        BeingDelayed = true
        SetMonsterWalkSpeed(0)
        task.wait(1)
        BeingDelayed = false
    else
        BeingDelayed = true
        SetMonsterWalkSpeed(60)
        task.wait(1)
        BeingDelayed = false
    end
end

local function ControlMonster()
    local FoundPlayerVisionPart = table.find(TouchingParts, 'PlayerVision') and true or false
    MonsterFreezed(FoundPlayerVisionPart)
end

--// Connections

-- Main Loop
while task.wait(0.1) do
    TouchingParts = GetTouchingParts(HitBox, Filter)
    ControlMonster()
end

Reply Soon!

2 Likes