让多个敌人跟随触发Unity

时间:2014-11-19 19:40:35

标签: unity3d navigation artificial-intelligence unityscript pathing

现在我正在做一个定时"逃避"主题游戏,玩家必须找到他们的船只碎片崩溃后才能离开这个星球。玩家必须避免最终会在整个关卡中追逐它们的敌人。

我目前的问题是弄清楚如何在触发后让多个敌人跟进。

现在只有一个跟随,但该区域的其他5个不动。我正在考虑将它们放入阵列中,但我不确定这是否会起作用,因为我需要访问navmeshagent组件

这是我的代码:

#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);
    }

}

1 个答案:

答案 0 :(得分:1)

您可以将代理变量的类型从NavMeshAgent更改为NavMeshAgent数组。在编辑器中,您可以设置数组的大小,然后分配您想要做出反应的所有敌人。然后你可以迭代它们并全部更新它们。这就是它的样子:

#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);
        }
    }
}

或者,您可以标记敌人并将FindGameObjectsWithTag与GetComponent结合使用。然后它看起来像这样:

#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);
        }
    }
}