You are already on the right track, spotting the fact the code is the same except in a very few locations. So fixing this shouldn't be hard. We first wrap this in a function, then we give that function an argument we call "parentFrame", then we can easily call the same code as many times as we like, and just provide it with a new frame to work with and do the exact operations.
Code:
local function SkinFrame(parentFrame)
local bg = CreateFrame('Frame', nil, parentFrame)
bg:SetPoint('TOPLEFT', parentFrame, 0, -26)
bg:SetPoint('BOTTOMRIGHT', parentFrame, 0, 26)
bg:SetBackdrop({
bgFile = [[Interface/Buttons/WHITE8X8]],
tiled = false,
insets = {left = -3, right = -2, top = -3, bottom = -3}
})
bg:SetBackdropColor(0, 0, 0, 1)
bg:SetFrameLevel(0)
local trans = CreateFrame('Frame', nil, parentFrame)
trans:SetBackdrop({
bgFile = [[Interface\Tooltips\UI-Tooltip-Background]],
tiled = false,
insets = {left = -6, right = -5, top = -6, bottom = -6}
})
trans:SetPoint('TOPLEFT', parentFrame, 0, -26)
trans:SetPoint('BOTTOMRIGHT', parentFrame, 0, 26)
trans:SetFrameLevel(0)
trans:SetFrameStrata('BACKGROUND')
trans:SetBackdropColor(0, 0, 0, 0.6)
end
SkinFrame(PlayerFrame)
SkinFrame(TargetFrame)
There is a final form of optimization we can do, though not a big thing considering it's ONLY used two times. Larger addons, let's say a raid frame with 80 potential units on screen, we could look at the two tables used in bg:SetBackdrop() and trans:SetBackdrop() and considering it's the same table used each time, we could make it so we just reuse the same table from memory, since the function creates a new table each time it is called.
Code:
local BG_BACKDROP = {
bgFile = [[Interface/Buttons/WHITE8X8]],
tiled = false,
insets = {left = -3, right = -2, top = -3, bottom = -3}
}
local TRANS_BACKDROP = {
bgFile = [[Interface\Tooltips\UI-Tooltip-Background]],
tiled = false,
insets = {left = -6, right = -5, top = -6, bottom = -6}
}
local function SkinFrame(parentFrame)
-- <snip>
bg:SetBackdrop(BG_BACKDROP)
-- <snip>
trans:SetBackdrop(TRANS_BACKDROP)
-- <snip>
end
myrroddin was quicker and replied while I was typing this out, but I'll hit the post button regardless.