• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Simple Way to Detect if Units in a Region belong to A Force

Nothing special here, I needed the code for a project of mine and thought others may find it useful. Can easily be modified to unit group
JASS:
function AreAnyUnitsInRegionInForce takes rect r, force f returns boolean
        local group regionUnits = CreateGroup()
        local unit currentUnit
        local boolean unitFound = false
    
        call GroupEnumUnitsInRect(regionUnits, r, null)
        loop
            set currentUnit = FirstOfGroup(regionUnits)
            exitwhen currentUnit == null
            if (IsUnitInForce(currentUnit, f)) then
                set unitFound = true
                exitwhen true
            endif
    
            call GroupRemoveUnit(regionUnits, currentUnit)
        endloop
        
        call DestroyGroup(regionUnits)
        set regionUnits = null
        set currentUnit = null
        
        return unitFound
endfunction
 
I would recommend posting this to Small Code Snippets

Presumably you just want a plain JASS solution, but there is nothing wrong with having it support globals to avoid creating/destroying a group. You could even use bj_lastCreatedGroup to access an always-alive-but-never-destroyed static group that works perfectly for FirstOfGroup loops.

JASS:
function AreAnyUnitsInRegionInForce takes rect r, force f returns boolean
    local unit currentUnit
    call GroupEnumUnitsInRect(bj_lastCreatedGroup, r, null)
    loop
        set currentUnit = FirstOfGroup(bj_lastCreatedGroup)
        exitwhen currentUnit == null
        if IsUnitInForce(currentUnit, f) then
            set currentUnit = null
            return true
        endif
        call GroupRemoveUnit(bj_lastCreatedGroup, currentUnit)
    endloop     
    return false
endfunction

For those who are on 1.31 or higher, they also have access to BlzGroupUnitAt, which is even better than a FirstOfGroup loop.

GroupEnumUnits... calls always empty the unit group prior to getting called, so you don't have to worry about leaving units in the global group.[/code]
 
Top