Random prefab Instantiate on a certain zone

i have a crab prefab, that I want to random place on the beach of islands that are on some neighbour terrains.

The beach is from the sea level to the grass zone. I have more islands:


THe islands are placed on neighbour terrains:
raado6

You could do something like Random.insideUnitSphere to get a 3D point to place them at. What have you already tried?

Perhaps as @leftshoe18_1 noted just place them randomly, but before emplacing them check the altitude of the ground at that point (raycast downwards) and if it is within your “sea level to the grass zone” height, make crab, otherwise pick again.

Be careful you don’t endlessly loop: only try it so many times, then give up, otherwise if you make a level with sheer steep cliffs on the islands, your crabs will have nowhere to spawn and the loop will lockup unless it has a given retry count.

Since the crab is an agent I tried this:


bool RandomPoint(Vector3 center, float range, out Vector3 result)
   {
       for (int i = 0; i < 30; i++)
       {
           Vector3 randomPoint = center + Random.insideUnitSphere * range;
           NavMeshHit hit;
           if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
           {
               result = hit.position;
               return true;
           }
       }
       result = Vector3.zero;
       return false;
   }
void Awake(){
      StartCoroutine(Spawn());
}
public IEnumarator Spawn(){
   int i = 0;
   Vecotr3 spawnPos;
   while(i < maxCrabs){
       if(RandomPoint(new Vector3(0, 0, 0), 7000f, out spawnPos)){
           if(Terrain.activeTerrain.SampleHeight(spawnPos) > seaLevel && Terrain.activeTerrain.SampleHeight(spawnPos) < grassLevel){
            //Instantiate crab
            yield return new WaitForEndOfFrame();
            i++;
            }
       }

   }
}

But I have more that 1 terrain so Terrain.activeTerrain doesn’t works and I can’t loop trough all Terrain.activeTerrains.

I solved it, thanks