Search code examples
unity-game-enginenavigationartificial-intelligenceunityscriptpath-finding

Make multiple enemies follow on trigger Unity


Right now I am making a timed "escape" themed game where the player must find pieces of their ship that have scattered upon crashing in order to get off the planet. The player must avoid the enemies that will end up chasing them throughout the level.

My current problem is figuring out how to get multiple enemies to follow once it is triggered.

Right now only the one follows but the other 5 in the area don't move. I was thinking about putting them into an array but I'm unsure if that will work as I need to access the navmeshagent component

Here is my code:

#pragma strict

//script by Kyle Crombie & Paul Christopher

    //will add negative action if collision is detected with player

var target : Transform; //the enemy's target 
var isSeen: boolean = false;

var agent: NavMeshAgent;

function OnTriggerStay() { 

    isSeen = true;
    target = GameObject.FindWithTag("Player").transform; //target the player

}

function Update () { 

    if(isSeen){
        agent.SetDestination(target.position);
    }

}

Solution

  • You can change the type of the agent variable from NavMeshAgent to array of NavMeshAgent. In the editor you can set the size of the array and then assign all the enemies you want to react. Then you can iterate over them and update them all. This is what it looks like:

    #pragma strict
    
    //script by Kyle Crombie & Paul Christopher
    //will add negative action if collision is detected with player
    
    var target : Transform; //the enemy's target 
    var isSeen: boolean = false;
    
    var agents : NavMeshAgent[]; // This is now an array!
    
    function OnTriggerStay() {
        isSeen = true;
        target = GameObject.FindWithTag("Player").transform; //target the player
    }
    
    function Update () {
        if(isSeen){
            for (var agent in agents) {
                agent.SetDestination(target.position);
            }
        }
    }
    

    Alternatively you could tag the enemies and use FindGameObjectsWithTag in combination with GetComponent. Then it looks like this:

    #pragma strict
    
    //script by Kyle Crombie & Paul Christopher
    //will add negative action if collision is detected with player
    
    var target : Transform; //the enemy's target 
    var isSeen: boolean = false;
    
    function OnTriggerStay() {
        isSeen = true;
        target = GameObject.FindWithTag("Player").transform; //target the player
    }
    
    function Update () {
        if(isSeen){
            for (var agent in GameObject.FindGameObjectsWithTag("Enemy")) {
                agent.GetComponent(NavMeshAgent).SetDestination(target.position);
            }
        }
    }