Search Unity

Spawning Trees on my map

Discussion in 'Scripting' started by Pereazy, Aug 5, 2020.

  1. Pereazy

    Pereazy

    Joined:
    Jul 16, 2020
    Posts:
    11
    Guys i want to place all over my map exept for a few places trees which i have a prefab for. But how can i do that without the paint trees tool, because otherwise i cannot put my tree script which makes me able to cut down the tree on it. Anyone got an idea? I want them to always stay at the same location so no random generating they should not move everytime the player loads in. I will welcome any idea :/ Btw im pretty new so dont be mad if that what i ask is pretty dumb. ^^
     
  2. mgrekt

    mgrekt

    Joined:
    Jun 22, 2019
    Posts:
    92
    I mean you can manually place them and have a script that respawns the tree back later.
     
  3. Pereazy

    Pereazy

    Joined:
    Jul 16, 2020
    Posts:
    11
    Well that would mean i would have to manually place 20000 trees (really i checked it with mass place trees) and that is not eaven my whole map. Is there no way to randomly place it all over my map?
     
  4. mgrekt

    mgrekt

    Joined:
    Jun 22, 2019
    Posts:
    92
    Well, I may not know how to solve this because I've never done anything similar, but I found something similar to what you want. https://forum.unity.com/threads/solved-placing-trees-with-scripts-on-terrain.462885/
     
  5. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    For any square shaped area (there are alterations for other shapes afaik) you can calculate mostly random spawn positions for objects with a radius using Poisson Disc Sampling. To place them on a terrain simply do a downwards raycast to check if the position actually lies on terrain, or water, rocks, caves, .. or other locations you do not want trees on. Then decide whether to spawn the tree or not. The PDS radius would be the radius of your trees to prevent overlapping and thus clipping.
    Be aware that 20k trees or objects in general is a huge number. You certainly do not want to instantiate each tree as its own game object and instead batch them up into larger groups using one mesh renderer. You may also want to look into chunking mechanisms, or only spawn the trees you actually need / can see, as i doubt you will ever need more than a couple hundred or so trees at a time. Since you want to have a script on each tree, which is not reasonably possible for 20k objects, you will have to do some trickery, running the script on each group and somehow only cut down the right tree - or separating the tree being cut down from the group and then dynamically adding that script to said tree.