Enemy Pooling on a Terrain

I use an object pooling system

	height = Terrain.activeTerrain.SampleHeight (enemy.transform.position)
		+ Terrain.activeTerrain.transform.position.y;

	Vector3 spawnPoint = new Vector3();

	spawnPoint.x = Random.Range (2000, 600);
	spawnPoint.y = (height.y);
	spawnPoint.z = Random.Range (1500, 3500);

This is what I try to use^

But because I use NavMesh it needs to be instantiated ON the terrain. My solution above does not work.

The question I pose is:
How would I script a bumpy terrains vector 3 height like I did above except work?

I’m pretty sure you have the right idea, you just need to subtract the terrain’s position. You want your enemy’s position to be relative to your terrain, so you nullify the terrain’s position by subtracting it so that if your terrain were at [-10, 0, -10] the result would be to add [10, 0, 10] to the enemy position.

Try this:

// TerrainSpawner.cs
using UnityEngine;

public class TerrainSpawner : MonoBehaviour {
    public void Spawn(Terrain terrain, GameObject template)
    {
        Bounds box = terrain.terrainData.bounds;

        // Get random position in terrain space
        Vector3 pos = new Vector3(Random.Range(box.min.x, box.max.x), 0, Random.Range(box.min.z, box.max.z));

        // Transform to world space
        pos += terrain.transform.position;

        // Sample height
        pos.y = terrain.SampleHeight(pos);

        Instantiate(template, pos, Quaternion.identity);
    }
}

Sample Usage:

public GameObject obj;

private void Start()
{
    for (var i = 0; i < 1000; i++)
        GetComponent<TerrainSpawner>().Spawn(Terrain.activeTerrain, obj);
}