Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by HuskyPanda213 · Jun 07, 2014 at 06:23 PM · editorterraintrees

Converting all terrain trees to gameobjects?

I am working on a script which is supposed to convert all of the terrain trees in the scene to gameobjects (I made a billboard script, and I need to have basic scripts on the trees). Now, the problem is that the trees are not in the correct position when instantiated -- I removed the code of destroying the terrain trees, and the trees instantiated are far from where they are supposed to be. Second, the trees do not respond to height. Please help me fix this problem. Thanks!

Code:

 using UnityEngine;
 using UnityEditor;
 using System.Collections;
 using System.Collections.Generic;
 
 [ExecuteInEditMode]
 public class CustomTreeBrush : EditorWindow
 {
 
     Terrain terrain;
 
     GameObject[] trees = new GameObject[4];
 
 
     [MenuItem ("Tools/Custom/Terrain")]
     static void Init()
     {
         CustomTreeBrush window = (CustomTreeBrush)GetWindow (typeof(CustomTreeBrush));
     }
 
     void OnGUI()
     {
         terrain = (Terrain)EditorGUILayout.ObjectField (terrain, typeof(Terrain), true);
 
         trees[0] = (GameObject)EditorGUILayout.ObjectField (trees[0], typeof(GameObject), true);
         trees[1] = (GameObject)EditorGUILayout.ObjectField (trees[1], typeof(GameObject), true);
         trees[2] = (GameObject)EditorGUILayout.ObjectField (trees[2], typeof(GameObject), true);
         trees[3] = (GameObject)EditorGUILayout.ObjectField (trees[3], typeof(GameObject), true);
 
         if(GUILayout.Button("Convert to objects"))
         {
             Convert();
         }
     //    if(GUILayout.Button("Debug"))
     //    {
     //    }
     }
 
     public void Convert()
     {
         TerrainData data = terrain.terrainData;
         float width = (float)data.heightmapWidth;
         float height = (float)data.heightmapHeight;
         foreach(TreeInstance tree in data.treeInstances)
         {
             Vector3 position = new Vector3(tree.position.x * width, tree.position.y, tree.position.z * height);
             Instantiate(trees[tree.prototypeIndex], position, Quaternion.identity);
         }
     }
 
 }
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jaqal · Jul 09, 2014 at 09:22 PM 0
Share

Where do you attach this script. I've been working on making terrain trees into objects for awhile now!

4 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Murkas · Jun 07, 2014 at 07:12 PM

You are using the width and height of the heightmap, which is basically the resolution of the heightmap. Try using

 public void Convert()
 {
   TerrainData data = terrain.terrainData;
   float width = data.size.x;
   float height = data.size.z;
   float y = data.size.y;
   foreach(TreeInstance tree in data.treeInstances)
   {
     Vector3 position = new Vector3(tree.position.x * width, tree.position.y*y, tree.position.z * height);
     Instantiate(trees[tree.prototypeIndex], position, Quaternion.identity);
   }
 }

instead. TerrainData.size is the actual size of the terrain in world units.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image HuskyPanda213 · Jun 07, 2014 at 08:57 PM 0
Share

Thank you! This fixed the problems. :)

avatar image xxhaissamxx · Jan 22, 2018 at 06:24 AM 0
Share

can do same for grass ? i tried

 foreach (DetailPrototype grass in data.detailPrototypes)
         {
             Vector3 position = new Vector3(grass.prototype.transform.position.x * width, grass.prototype.transform.position.y * y, grass.prototype.transform.position.z * height);
             Instantiate(trees[0], position, Quaternion.identity);
         }

avatar image joeysipos · Apr 17, 2021 at 01:21 AM 0
Share

I spruced up your code some more. Just hit the checkbox populateTrees in the editor, and will extract all the trees (with correct scale) and place them under whatever gameojbect this attached to.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEditor;
 
 
 
 [ExecuteInEditMode]
 public class TreeExtractor : MonoBehaviour
 {
     public bool populateTrees;
     public Terrain terrain;
     public List<GameObject> trees;
 
     private void Update()
     {
         if (populateTrees == true)
         {
             Convert();
             populateTrees = false;
         }
     }
 
     public void Convert()
     {
         GameObject allTrees = new GameObject("AllTrees"); //All trees will be placed under this gameobject 
         allTrees.transform.parent = transform; //make allTrees a parent of this transform
 
         TerrainData data = terrain.terrainData;
         float width = data.size.x;
         float height = data.size.z;
         float y = data.size.y;
         TreePrototype[] treeProtoypes =  terrain.terrainData.treePrototypes; // get tree prototypes on the terrain
         foreach (TreePrototype treeProtoype in treeProtoypes) //extract the tree prefabs into the Gameobject list
         {
             trees.Add(treeProtoype.prefab.gameObject); 
         }
 
         //place the trees
         foreach (TreeInstance tree in data.treeInstances)
         {
             
             Vector3 position = new Vector3(tree.position.x * width, tree.position.y * y, tree.position.z * height);
             Vector3 scale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale);
             GameObject treeToBePlaced = trees[tree.prototypeIndex];
             treeToBePlaced.transform.localScale = scale;
             Instantiate(treeToBePlaced, position, Quaternion.identity, allTrees.transform);
         }
     }
 }
avatar image
2

Answer by lex24 · Jun 28, 2019 at 01:25 PM

I have updated this script. It now takes tree prefabs from Terrain. It also sets position, rotation and scale of generated tree game objects correctly (according to terrain data):

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEditor;
 // Replaces Unity terrain trees with prefab GameObject.
 // http://answers.unity3d.com/questions/723266/converting-all-terrain-trees-to-gameobjects.html
 [ExecuteInEditMode]
 public class TreeReplacerS : EditorWindow {
     [Header("References")]
     public Terrain _terrain;
     //============================================
     [MenuItem("Window/My/TreeReplacer")]
     static void Init()
     {
         TreeReplacerS window = (TreeReplacerS)GetWindow(typeof(TreeReplacerS));
     }
     void OnGUI()
     {
         _terrain = (Terrain)EditorGUILayout.ObjectField(_terrain, typeof(Terrain), true);
         if (GUILayout.Button("Convert to objects"))
         {
             Convert();
         }
         if (GUILayout.Button("Clear generated trees"))
         {
             Clear();
         }
     }
     //============================================
     public void Convert()
     {
         TerrainData data = _terrain.terrainData;
         float width = data.size.x;
         float height = data.size.z;
         float y = data.size.y;
         // Create parent
         GameObject parent = GameObject.Find("TREES_GENERATED");
         if (parent == null)
         {
             parent = new GameObject("TREES_GENERATED");
         }
         // Create trees
         foreach (TreeInstance tree in data.treeInstances)
         {
             if (tree.prototypeIndex>=data.treePrototypes.Length)
                 continue;
             var _tree = data.treePrototypes[tree.prototypeIndex].prefab;
             Vector3 position = new Vector3(
                 tree.position.x * width,
                 tree.position.y*y,
                 tree.position.z * height) + _terrain.transform.position;
             Vector3 scale = new Vector3(tree.widthScale,tree.heightScale,tree.widthScale);
             GameObject go = Instantiate(_tree, position, Quaternion.Euler(0f,Mathf.Rad2Deg*tree.rotation,0f), parent.transform) as GameObject;
             go.transform.localScale  = scale;
         }
     }
     public void Clear()
     {
         DestroyImmediate(GameObject.Find("TREES_GENERATED"));
     }
 }

@anunnaki2016 to use this script you need to save it at Assets/Editor/TreeReplacerS.cs. Now you are able to open this tool with Window/My/TreeReplacer menu item.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Velo222 · Jan 19, 2020 at 01:28 AM 0
Share

Exactly what I was looking for thank you! I can now replace tree instances placed with the terrain system with real gameobjects. Great for simulating chopping down trees, with the performance of using the terrain system.

avatar image
0

Answer by Stardog · Oct 12, 2017 at 09:33 PM

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEditor;

 // Replaces Unity terrain trees with prefab GameObject.
 // http://answers.unity3d.com/questions/723266/converting-all-terrain-trees-to-gameobjects.html
 [ExecuteInEditMode]
 public class TreeReplacerS : EditorWindow {

 [Header("Settings")]
 public GameObject _tree;

 [Header("References")]
 public Terrain _terrain;

 //============================================

 [MenuItem("Window/My/TreeReplacer")]
 static void Init()
 {
     TreeReplacerS window = (TreeReplacerS)GetWindow(typeof(TreeReplacerS));
 }

 void OnGUI()
 {
     _terrain = (Terrain)EditorGUILayout.ObjectField(_terrain, typeof(Terrain), true);

     _tree = (GameObject)EditorGUILayout.ObjectField(_tree, typeof(GameObject), true);

     if (GUILayout.Button("Convert to objects"))
     {
         Convert();
     }

     if (GUILayout.Button("Clear generated trees"))
     {
         Clear();
     }
 }

 //============================================

 public void Convert()
 {
     TerrainData data = _terrain.terrainData;
     float width = data.size.x;
     float height = data.size.z;
     float y = data.size.y;

     // Create parent
     GameObject parent = GameObject.Find("TREES_GENERATED");

     if (parent == null)
     {
         parent = new GameObject("TREES_GENERATED");
     }

     // Create trees
     foreach (TreeInstance tree in data.treeInstances)
     {
         //Vector3 position = new Vector3(tree.position.x * width, tree.position.y * y, tree.position.z * height);
         Vector3 position = new Vector3(tree.position.x * data.detailWidth - (data.size.x / 2), tree.position.y * y - (data.size.y / 2), tree.position.z * data.detailHeight - (data.size.z / 2));

         //Instantiate(_trees[tree.prototypeIndex], position, Quaternion.identity, parent.transform);
         Instantiate(_tree, position, Quaternion.identity, parent.transform);
     }
 }

 public void Clear()
 {
     DestroyImmediate(GameObject.Find("TREES_GENERATED"));
 }

 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by unity_0yHbwFRBfNCNxw · Jun 10, 2021 at 03:00 PM

Thank you for that script @joeysipos its realy usefull for me. Another question to all of you. Is there a way of converting the terrain ground to gameobject? I am a C# & Unity beginner. For any suggestion I would be very happy.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

31 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Scripts on Terrain Trees 2 Answers

Why is my tree so gigantic? 2 Answers

Do all trees sway the same? And do bushes for that matter? 1 Answer

Scripts on tree prefab don't respond? 1 Answer

Where are my trees? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges