This script will work fine if i have a terrain in the scene but i don't have a terrain this case :
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class SpawnObjects : MonoBehaviour
{
public GameObject prefab;
public Terrain terrain;
public int numberOfObjects;
public float duration;
public float yOffset = 0.5f;
private float terrainWidth;
private float terrainLength;
private float xTerrainPos;
private float zTerrainPos;
void Awake()
{
//Get terrain size
terrainWidth = terrain.terrainData.size.x;
terrainLength = terrain.terrainData.size.z;
//Get terrain position
xTerrainPos = terrain.transform.position.x;
zTerrainPos = terrain.transform.position.z;
StartCoroutine(Generate());
}
IEnumerator Generate()
{
//Generate the Prefab on the generated position
for (int i = 0; i < numberOfObjects; i++)
{
//Generate random x,z,y position on the terrain
float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));
//Apply Offset if needed
yVal = yVal + yOffset;
GameObject objInstance = (GameObject)Instantiate(prefab,
new Vector3(randX, yVal, randZ), Quaternion.identity);
if (duration > 0)
{
yield return new WaitForSeconds(duration);
}
}
}
}
In my scene i have some mountains objects not my own it's from a package. and i want to spawn random objects around the mountains.
example of one of the mountains objects :

