Created
October 24, 2022 16:13
-
-
Save STARasGAMES/01d7211cdbaebecbfb6064bb2436fab2 to your computer and use it in GitHub Desktop.
Add this script to your unity terrain object, and at startup it will convert terrain trees into actual scene objects. While in editor it may floode hierarchy, so by default all instantiated trees are hidden and non-selectable. You can change this behavior in the inspector.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace Impostors.Utilities | |
{ | |
public class TerrainTreesToSceneObjectsConverter : MonoBehaviour | |
{ | |
[SerializeField] | |
private Terrain _terrain = default; | |
[SerializeField] | |
private Transform _treesParent = default; | |
[SerializeField] | |
private bool _convertOnAwake = true; | |
[SerializeField] | |
private HideFlags _hideFlagsForCreatedTrees = HideFlags.HideAndDontSave; | |
void Awake() | |
{ | |
if (_convertOnAwake) | |
Convert(); | |
} | |
public void Convert() | |
{ | |
if (_treesParent == null) | |
_treesParent = _terrain.transform; | |
var terrainData = _terrain.terrainData; | |
var prototypes = terrainData.treePrototypes; | |
foreach (var treePrototype in prototypes) | |
{ | |
treePrototype.prefab.SetActive(false); | |
} | |
var instances = terrainData.treeInstances; | |
var terrainSize = _terrain.terrainData.size; | |
for (int i = 0; i < instances.Length; i++) | |
{ | |
var instance = instances[i]; | |
var prefab = prototypes[instance.prototypeIndex].prefab; | |
var rotation = Quaternion.Euler(0, instance.rotation * Mathf.Rad2Deg, 0); | |
var position = instance.position; | |
position.x *= terrainSize.x; | |
position.y *= terrainSize.y; | |
position.z *= terrainSize.z; | |
var tree = Instantiate(prefab, position, rotation, _treesParent).transform; | |
var scale = tree.localScale; | |
scale.x *= instance.widthScale; | |
scale.y *= instance.heightScale; | |
scale.z *= instance.widthScale; | |
tree.localScale = scale; | |
tree.GetComponent<ImpostorLODGroup>().RecalculateBounds(); | |
tree.gameObject.SetActive(true); | |
tree.gameObject.hideFlags = _hideFlagsForCreatedTrees; | |
} | |
foreach (var treePrototype in prototypes) | |
{ | |
treePrototype.prefab.SetActive(true); | |
} | |
_terrain.treeDistance = 0; | |
_terrain.treeBillboardDistance = float.MaxValue; | |
_terrain.treeMaximumFullLODCount = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment