#Help me optimize this script.

3 messages · Page 1 of 1 (latest)

gaunt kayak
#

I have a script to highlight a part when the player hovers over it if it has the "Highlightable" tag. Is there anyway to better optimize this?

local CollectionService = game:GetService("CollectionService")


local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local DefaultMaxDistance = 10 -- How close the player has to be to highlight the object

mouse.Move:Connect(function()
    if not mouse.Target then script.Highlight.Adornee = nil return end -- If the mouse has no Target
    
    local distanceToTarget = (player.Character.HumanoidRootPart.Position - mouse.Target.Position).Magnitude
    
    if mouse.Target:FindFirstChildWhichIsA("ClickDetector") then
        if distanceToTarget >= mouse.Target:FindFirstChildWhichIsA("ClickDetector").MaxActivationDistance then return end -- Checks if there is a click detector in the target, if so, set highlight's max distance to the MaxActivationDistance
    elseif mouse.Target.Parent:FindFirstChildWhichIsA("ClickDetector")  then
        if distanceToTarget >= mouse.Target.Parent:FindFirstChildWhichIsA("ClickDetector").MaxActivationDistance then return end -- Same thing but for target's parent
    else
        if distanceToTarget >= DefaultMaxDistance then return end -- If the part is too far away and there is no ClickDetector found
    end
    
    if CollectionService:HasTag(mouse.Target,"Highlightable") then -- If the target is highlightable
        script.Highlight.Adornee = mouse.Target
        return
    elseif CollectionService:HasTag(mouse.Target.Parent,"Highlightable") then -- If the target's parent is highlightable
        script.Highlight.Adornee = mouse.Target.Parent
        return
    end
    script.Highlight.Adornee = nil
end)

I'm not sure if I should use RunService instead of mouse.Move, or if there is a better way to get the distance.

lunar narwhal
#

E

crude ferry
#

use mouse.move