Here's what I've come up with along with some tweaks and optimizations.
Lua Code:
local AddOnPath=("Interface\\AddOns\\%s\\"):format(...);-- Dynamically fetch our addon path
local Frame=CreateFrame("ScrollingMessageFrame",nil,UIParent)
Frame:SetSize(450,200)
Frame:SetPoint("CENTER")
Frame:SetFont(AddOnPath.."Res\\PHA_.TTF",30,"THICKOUTLINE")
Frame:SetShadowColor(0.00,0.00,0.00,0.75)
Frame:SetShadowOffset(3.00,-3.00)
Frame:SetJustifyH("CENTER")
Frame:SetMaxLines(2)
--Frame:SetInsertMode("BOTTOM")
Frame:SetTimeVisible(2)
Frame:SetFadeDuration(1)
Frame:RegisterEvent("PLAYER_LOGIN")
Frame:RegisterUnitEvent("UNIT_PET","player")
Frame:RegisterUnitEvent("UNIT_HEALTH","pet")
local LowHealthThreshold=0.35;
local LastHealthValue=0;
Frame:SetScript("OnEvent",function(self)
if UnitExists("pet") then-- Check if pet exists
local cur,max=UnitHealth("pet"),UnitHealthMax("pet");
if cur and max and max>0 then-- Check if we have health data
if cur<LastHealthValue then-- Has health decreased?
if cur<=0 then-- Is pet dead?
PlaySoundFile(AddOnPath.."Res\\PHA.ogg")
self:AddMessage("- PET DEAD -", 1, 0, 0, nil, 3)
elseif cur/max<=LowHealthThreshold then-- Is pet low health?
PlaySoundFile(AddOnPath.."Res\\PHA.ogg")
self:AddMessage("- CRITICAL PET HEALTH -", 1, 0.5, 0, nil, 3)
end
end
LastHealthValue=cur;-- Update tracking value
else LastHealthValue=0; end-- Reset to zero if health not available yet
else LastHealthValue=0; end-- Reset to zero if no pet
end)