Set Destination (NavMesh) not working with instantiate

So i have an enemy on nav mesh but when i Instantiate the enemy i get this error

“SetDestination” can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.NavMeshAgent:SetDestination(Vector3)
NavMeshScript:Update() (at Assets/My Scripts/NavMeshScript.cs:18)

this is my nav mesh script using
UnityEngine;
using System.Collections;

public class NavMeshScript : MonoBehaviour 
{

	public Transform target;
	NavMeshAgent agent;
	// Use this for initialization
	void Start () 
	{
		agent = GetComponent<NavMeshAgent> ();
	}
	
	// Update is called once per frame
	void Update () 
	{

		agent.SetDestination(target.position);
	}
}

this is my instantiate script

#pragma strict

var prefab : Transform;
	
function Update ()
{
    if (Input.GetKeyDown("g"))
    {
	    for (var i : int = 0;i < 10; i++) 
	    {
		    Instantiate (prefab, Vector3(i * 2.0, 0, 0), Quaternion.identity);
	    }
    }
}

The navmesh agent has to have it’s center pretty close to the navmesh on the y-axis, otherwise it reports being “not placed on the navmesh”. Usually this error message means “your navmesh agent is above or below the navmesh!”.

When you place stuff on the mesh manually in the inspector, and press play, you can often see that they move a bit up or down to align with the mesh. When you instantiate something, you don’t get that help.

A hack would be to place a thing on the navmesh, record and store it’s Y-position, delete it, and set newly instantiated objects to that Y-level. That should fix it, probably.

A less hacky solution is NavMesh.SamplePosition:

This will find the nearest point on the navmesh to a given Vector3, e.g.

 for (var i : int = 0;i < 10; i++) 
         {
             Vector3 randomPosition = new Vector3(i*2f, 0f, 0f);
             NavMeshHit hit;
             if(NavMesh.SamplePosition(randomPosition, out hit, 100f, NavMesh.AllAreas){ 
                 Instantiate (prefab, hit.position, Quaternion.identity);
             }
         }