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);
}