Search Unity

Resolved Random tree spawner

Discussion in 'Scripting' started by glacierqsr, Feb 1, 2023.

  1. glacierqsr

    glacierqsr

    Joined:
    Nov 9, 2021
    Posts:
    11
    So I'm making a random tree spawner however, the trees are spawning outside of the terrain bounds. Any ideas as to what I need to change to fix this? Image of the current results is this https://flic.kr/p/2oeJqCu
    Code (CSharp):
    1. public class TreeSpawner : MonoBehaviour{
    2.     public GameObject treePrefab, treeParent;
    3.     public int treeAmount;
    4.     List<GameObject> treesList = new List<GameObject>();
    5.     GameObject[] treesArray;
    6.  
    7.     public GameObject Terrain;
    8.  
    9.     void Start(){
    10.         Vector3 TerrainSize = Vector3.Scale(transform.localScale, Terrain.GetComponent<MeshCollider>().bounds.size);
    11.      
    12.         for (int i = 0; i <= treeAmount; i++){
    13.             treesList.Add(Instantiate<GameObject>(treePrefab));
    14.             treesArray = treesList.ToArray();
    15.             treesArray[i].transform.position = new Vector3(Random.Range(TerrainSize.x ,TerrainSize.y), 0, Random.Range(TerrainSize.x, TerrainSize.y));
    16.             treesArray[i].transform.parent = treeParent.transform;
    17.         }
    18.     }
    19. }
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    Just look at your random range methods. The answer should be pretty obvious.
     
  3. glacierqsr

    glacierqsr

    Joined:
    Nov 9, 2021
    Posts:
    11
    may or may not have forgotten how vectors work, thanks for the comment.
    upload_2023-2-2_0-37-16.png
     

    Attached Files:

    RadRedPanda likes this.