1.
实例化敌人并将其添加到列表中(在您的脚本中):
using UnityEngine;
public class Controller: MonoBehaviour
{
GameObject enemyPrefab;
List<GameObject> enemiesList = new List<GameObject>();
void Start()
{
GameObject enemy = Instantiate(enemiePrefab, transform.position, transform.rotation);
enemiesList.Add(enemy);
}
}
2。
让物体在你的寻路中移动:
有很多方法可以做到这一点,但我建议你将不同的waypoints 存储在列表、数组或任何你想要的东西中。
然后让你的敌人一个接一个地跟随。
所以现在你的主脚本应该是这样的:
using UnityEngine;
public class Controller : MonoBehaviour
{
public GameObject enemyPrefab;
private List<GameObject> enemiesList = new List<GameObject>();
public List<GameObject> wayPoints = new List<GameObject>();
void Start()
{
GameObject enemy = Instantiate(enemiePrefab, transform.position, transform.rotation);
enemy.wayPoints = wayPoints;
enemiesList.Add(enemy);
}
}
你的敌人脚本应该是这样的:
using UnityEngine;
public class Enemy : MonoBehaviour
{
public List<GameObject> wayPoints = new List<GameObject>();
public float speed;
private Transform target;
int waypointIndex = 0;
private void Start()
{
target = List[waypointIndex].transform;
waypointIndex++;
}
void Update()
{
// The step size is equal to speed times frame time.
float step = speed * Time.deltaTime;
// Move our position a step closer to the target.
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
//If we arrive to the target, get the new target
if(this.transform.position == target.position)
{
waypointIndex++;
//if it is the last element, go to the first one again
if(wayPointIndex > List.Count())
{
wayPointIndex = 0;
}
target = List[waypointIndex].transform;
}
}
}
请注意,您可以更改代码,以便您的控制器也移动每个敌人,但这取决于您!