1.
Instantiate enemy and add it to a list (which is in your script):
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.
Make the object move on your pathfinding:
There are many ways to do that, but I suggest you to store in a List, array or whatever you want, the different waypoints that you have.
Then make your enemies follow one waypoint after another.
So now your main script should look like:
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);
}
}
And your enemy script should look like:
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;
}
}
}
Note that you can alterate the code so your controller also moves every enemy, but that's up to you!