- Home /
Question by
GabrielPP312 · Nov 25, 2020 at 01:26 AM ·
terrainobjectspawn
Create objects above the terrain
I did a terrain generator code, and a trees generator code too, the trees "spawn" sometimes fying and sometimes half under the terrain and half above, what can I do to make the trees spawn exatcly with the bottom in the terrain? Here is the code:
using UnityEngine;
public class TreeGenerator : MonoBehaviour
{
[SerializeField] GameObject treeType1;
[SerializeField] GameObject treeType2;
[SerializeField] int treeAmount;
[SerializeField] int treeAmount2;
void Start(){
GenerateTrees();
}
void GenerateTrees(){
for(int i = 0; i < treeAmount; i++){
GameObject trees = Instantiate(
treeType1, new Vector3(
Random.Range(1, 2000),
Random.Range(1, 20),
Random.Range(1, 2000)),
Quaternion.identity
);}
for(int i = 0; i < treeAmount2; i++){
GameObject trees = Instantiate(
treeType2, new Vector3(
Random.Range(1, 2000),
Random.Range(1, 20),
Random.Range(1, 2000)),
Quaternion.identity);
}
}
}
Comment
Answer by Llama_w_2Ls · Nov 25, 2020 at 01:56 AM
You can create this effect by storing all points on the terrain in a list or dictionary, especually the y-values, and rabdomly select points from there to be your tree pos on the terrain