Spawned Enemy Waypoints

If I'm instantiating enemy prefabs in order to spawn them, any idea how I can tell them what their waypoints are? Prefabs aren't letting me give them targets. I know why they don't but I don't know the alternative, help please.

var waypoint : Transform[];
var currentWaypoint : int;
var speed : float = 20;

function Update(){
    if(currentWaypoint < waypoint.length){
        var target = waypoint[currentWaypoint].transform.position;
        var moveDirection : Vector3 = target - transform.position;
        var velocity = rigidbody.velocity;
        if(moveDirection.magnitude < 1){
            currentWaypoint++;
        }else{
            velocity = moveDirection.normalized * speed;
        }
    }
    rigidbody.velocity = velocity;
}

  • If the problem is you want to spawn them on instantiation in some spawnpoint:

You can use GameObject.FindGameObjectsWithTag in Start or Awake of a script attached to the enemy.

Example:

public class SpawnOnStart : MonoBehavior
{
    void Start()
    {
        var spawns = GameObject.FindGameObjectsWithTag("Spawn");
        var randomSpawn = spawns[Random.Range(0, spawns.Length - 1)];
        transform.position = randomSpawn.transform.position;
        transform.rotation = randomSpawn.transform.rotation;
    }
}

  • If the problem is you want to spawn them and give them a waypoint to follow:

Your prefab should contain some sort of script that control them, and you should know which waypoint they should follow. Then it's a matter of creating the enemy, getting the script that handles the waypoints and set its waypoint. This is obviously implemented differently with regard to your particular setup.

Example:

 // In method that instantiate the prefab:
 enemy = (GameObject)Instantiate(prefab, position, rotation);
 var enemyScript = enemy.GetComponent<YourScript>();
 enemyScript.waypoint = someWaypoint;