NPC/GetEnemy

From Garry's Mod
Jump to: navigation, search
 NPC:GetEnemy( )

Contents

Description

Returns the entity that this NPC is trying to fight.

BUG

This returns nil if the NPC has no enemy. You should use IsValid (which accounts for nil and NULL) on the return to verify validity of the enemy.

Issue Tracker: #3132

Returns

NPC

Enemy NPC.

Examples

Example

Kill any npc that sets the first player as its enemy.

local function Think( )
	for k, v in pairs( ents.GetAll( ) ) do
		if v:IsNPC( ) and v:GetEnemy( ) == Entity( 1 ) then
			v:TakeDamage( 999 )
		end
	end
end

hook.Add( "Think", "Kill My Enemies", Think )

Output:

Any npc that sets their enemy to Entity( 1 ) dies.

Examples

Example

Make every NPC that does not have an enemy (and preferably a D_HT relationship agains Players) start attacking a random Player. This code is copied from the gamemode My Base Defence:

-- ...
local function _SetRandomPlayerTargetForNPC(npc)
	if (npc:IsNPC()) then
		if (!IsValid(npc:GetEnemy())) then
			local _allPlayers	= player.GetAll()
			local _winnerPlNr	= math.random(1, #_allPlayers)

			timer.Simple(0.15, function()
				local __Player = _allPlayers[_winnerPlNr]
				--
				--- Set the enemy for the NPC, so it does not just stand there doing nothing
				-- lika young lazy teen or something
				if (!npc:IsValid() or !__Player:IsValid()) then return end
				npc:SetEnemy(__Player)
				npc:UpdateEnemyMemory(__Player, __Player:GetPos())
				npc:SetSchedule(SCHED_SHOOT_ENEMY_COVER)
			end)
		end
	end
end
-- - - ---
-- --
-- Make every NPC that might not have a target, recive one random Player..:>>
-- (..you can place this loop inside an interval timer or something...)
for _, v in pairs(ents.GetAll('npc_*')) do
	if v:IsValid() then _SetRandomPlayerTargetForNPC(v) end
end

Output:

All NPCs on the SERVER will get their memory updated if they don't already have an enemy, and start moving to the last know position of the enemy and try to attack. This enemy will be a random Player. They will also try and shoot enemy cover.
Personal tools
Navigation