function ReplaceUnitBJ takes unit whichUnit, integer newUnitId, integer unitStateMethod returns unit
local unit oldUnit = whichUnit
local unit newUnit
local boolean wasHidden
local integer index
local item indexItem
local real oldRatio
if (oldUnit == null) then
set bj_lastReplacedUnit = oldUnit
return oldUnit
endif
set wasHidden = IsUnitHidden(oldUnit)
call ShowUnit(oldUnit, false)
if (newUnitId == 'ugol') then
set newUnit = CreateBlightedGoldmine(GetOwningPlayer(oldUnit), GetUnitX(oldUnit), GetUnitY(oldUnit), GetUnitFacing(oldUnit))
else
set newUnit = CreateUnit(GetOwningPlayer(oldUnit), newUnitId, GetUnitX(oldUnit), GetUnitY(oldUnit), GetUnitFacing(oldUnit))
endif
if (unitStateMethod == bj_UNIT_STATE_METHOD_RELATIVE) then
if (GetUnitState(oldUnit, UNIT_STATE_MAX_LIFE) > 0) then
set oldRatio = GetUnitState(oldUnit, UNIT_STATE_LIFE) / GetUnitState(oldUnit, UNIT_STATE_MAX_LIFE)
call SetUnitState(newUnit, UNIT_STATE_LIFE, oldRatio * GetUnitState(newUnit, UNIT_STATE_MAX_LIFE))
endif
if (GetUnitState(oldUnit, UNIT_STATE_MAX_MANA) > 0) and (GetUnitState(newUnit, UNIT_STATE_MAX_MANA) > 0) then
set oldRatio = GetUnitState(oldUnit, UNIT_STATE_MANA) / GetUnitState(oldUnit, UNIT_STATE_MAX_MANA)
call SetUnitState(newUnit, UNIT_STATE_MANA, oldRatio * GetUnitState(newUnit, UNIT_STATE_MAX_MANA))
endif
elseif (unitStateMethod == bj_UNIT_STATE_METHOD_ABSOLUTE) then
call SetUnitState(newUnit, UNIT_STATE_LIFE, GetUnitState(oldUnit, UNIT_STATE_LIFE))
if (GetUnitState(newUnit, UNIT_STATE_MAX_MANA) > 0) then
call SetUnitState(newUnit, UNIT_STATE_MANA, GetUnitState(oldUnit, UNIT_STATE_MANA))
endif
elseif (unitStateMethod == bj_UNIT_STATE_METHOD_DEFAULTS) then
elseif (unitStateMethod == bj_UNIT_STATE_METHOD_MAXIMUM) then
call SetUnitState(newUnit, UNIT_STATE_LIFE, GetUnitState(newUnit, UNIT_STATE_MAX_LIFE))
call SetUnitState(newUnit, UNIT_STATE_MANA, GetUnitState(newUnit, UNIT_STATE_MAX_MANA))
else
endif
call SetResourceAmount(newUnit, GetResourceAmount(oldUnit))
if (IsUnitType(oldUnit, UNIT_TYPE_HERO) and IsUnitType(newUnit, UNIT_TYPE_HERO)) then
call SetHeroXP(newUnit, GetHeroXP(oldUnit), false)
set index = 0
loop
set indexItem = UnitItemInSlot(oldUnit, index)
if (indexItem != null) then
call UnitRemoveItem(oldUnit, indexItem)
call UnitAddItem(newUnit, indexItem)
endif
set index = index + 1
exitwhen index >= bj_MAX_INVENTORY
endloop
endif
if wasHidden then
call KillUnit(oldUnit)
call RemoveUnit(oldUnit)
else
call RemoveUnit(oldUnit)
endif
set bj_lastReplacedUnit = newUnit
return newUnit
endfunction