Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- using Object = UnityEngine.Object;
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- [RequireComponent(typeof(Terrain))]
- public class ConvertTreesToGameObject : MonoBehaviour
- {
- [SerializeField]
- private Terrain terrain;
- private void Reset()
- {
- terrain = GetComponent<Terrain>();
- }
- [ContextMenu("Extract")]
- public void Extract()
- {
- List<GameObject> children = new List<GameObject>();
- foreach (Transform child in transform)
- {
- //Skip the first, since its the terrain itself
- if(child == transform) continue;
- children.Add(child.gameObject);
- }
- foreach (GameObject child in children)
- {
- //Remove all previously created objects first
- DestroyImmediate(child);
- }
- for (int i = 0; i < terrain.terrainData.treePrototypes.Length; i++)
- {
- TreePrototype tree = terrain.terrainData.treePrototypes[i];
- //Get all instances matching the prefab index
- TreeInstance[] instances = terrain.terrainData.treeInstances.Where(x => x.prototypeIndex == i).ToArray();
- for (int j = 0; j < instances.Length; j++)
- {
- //Un-normalize positions so they're in world-space
- instances[j].position = Vector3.Scale(instances[j].position, terrain.terrainData.size);
- instances[j].position += terrain.GetPosition();
- #if UNITY_EDITOR
- GameObject instance = PrefabUtility.InstantiatePrefab(tree.prefab, this.transform) as GameObject;
- #else
- GameObject instance = Object.Instantiate(tree.prefab.gameObject, this.transform);
- #endif
- instance.name = tree.prefab.name + j;
- instance.transform.position = instances[j].position;
- instance.transform.rotation = Quaternion.Euler(0f, Mathf.Rad2Deg * instances[j].rotation, 0f);
- instance.transform.localScale = new Vector3(instances[j].widthScale, instances[j].heightScale, instances[j].widthScale);
- }
- }
- }
- }
- #if UNITY_EDITOR
- [CustomEditor(typeof(ConvertTreesToGameObject))]
- class ConvertTreesToPrefabInspector : Editor
- {
- private ConvertTreesToGameObject script;
- private void OnEnable()
- {
- script = (ConvertTreesToGameObject)target;
- }
- public override void OnInspectorGUI()
- {
- base.OnInspectorGUI();
- if (GUILayout.Button("Extract trees"))
- {
- script.Extract();
- }
- }
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement