我目前正在制作一个限时“逃生”主题的游戏,玩家必须找到在坠毁时散落的飞船部件,以便离开星球。玩家必须避开在关卡中追赶他们的敌人。
我当前的问题是如何让多个敌人在触发后开始跟随。
目前只有一个敌人会跟随,而区域内的其他五个敌人则不动。我考虑将它们放入一个数组中,但我不确定这是否可行,因为我需要访问navmeshagent组件。
这是我的代码:
#pragma strict//script by Kyle Crombie & Paul Christopher //will add negative action if collision is detected with playervar 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); }}
回答:
你可以将agent变量的类型从NavMeshAgent更改为NavMeshAgent数组。在编辑器中,你可以设置数组的大小,然后分配所有你希望做出反应的敌人。然后你可以遍历它们并更新它们。看起来是这样的:
#pragma strict//script by Kyle Crombie & Paul Christopher//will add negative action if collision is detected with playervar 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 playervar 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); } }}