104 lines
3.2 KiB
C#
104 lines
3.2 KiB
C#
using UnityEngine;
|
||
using UnityEditor;
|
||
using System.Collections.Generic;
|
||
|
||
public class BatchAddTreesToTerrain : EditorWindow
|
||
{
|
||
Terrain targetTerrain;
|
||
List<GameObject> treePrefabs = new List<GameObject>();
|
||
|
||
[MenuItem("Tools/Terrain/Batch Add Trees")]
|
||
static void OpenWindow()
|
||
{
|
||
GetWindow<BatchAddTreesToTerrain>("Batch Add Trees");
|
||
}
|
||
|
||
void OnGUI()
|
||
{
|
||
GUILayout.Label("🌲 批量添加树到 Terrain", EditorStyles.boldLabel);
|
||
targetTerrain = (Terrain)EditorGUILayout.ObjectField("目标 Terrain", targetTerrain, typeof(Terrain), true);
|
||
|
||
EditorGUILayout.Space();
|
||
GUILayout.Label("树 Prefab 列表", EditorStyles.boldLabel);
|
||
|
||
// 拖拽区域
|
||
var dropArea = GUILayoutUtility.GetRect(0, 50, GUILayout.ExpandWidth(true));
|
||
GUI.Box(dropArea, "将 Tree Prefab 拖到这里");
|
||
|
||
// 检测拖入
|
||
Event evt = Event.current;
|
||
if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
|
||
{
|
||
if (dropArea.Contains(evt.mousePosition))
|
||
{
|
||
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
|
||
|
||
if (evt.type == EventType.DragPerform)
|
||
{
|
||
DragAndDrop.AcceptDrag();
|
||
foreach (var obj in DragAndDrop.objectReferences)
|
||
{
|
||
if (obj is GameObject go)
|
||
{
|
||
if (!treePrefabs.Contains(go))
|
||
treePrefabs.Add(go);
|
||
}
|
||
}
|
||
evt.Use();
|
||
}
|
||
}
|
||
}
|
||
|
||
// 展示列表 + 删除按钮
|
||
int removeIndex = -1;
|
||
for (int i = 0; i < treePrefabs.Count; i++)
|
||
{
|
||
EditorGUILayout.BeginHorizontal();
|
||
treePrefabs[i] = (GameObject)EditorGUILayout.ObjectField(treePrefabs[i], typeof(GameObject), false);
|
||
if (GUILayout.Button("X", GUILayout.Width(20)))
|
||
removeIndex = i;
|
||
EditorGUILayout.EndHorizontal();
|
||
}
|
||
|
||
if (removeIndex >= 0)
|
||
treePrefabs.RemoveAt(removeIndex);
|
||
|
||
EditorGUILayout.Space();
|
||
|
||
if (GUILayout.Button("✅ 添加到 Terrain"))
|
||
{
|
||
AddTreesToTerrain();
|
||
}
|
||
}
|
||
|
||
void AddTreesToTerrain()
|
||
{
|
||
if (targetTerrain == null)
|
||
{
|
||
Debug.LogWarning("请指定目标 Terrain!");
|
||
return;
|
||
}
|
||
|
||
TerrainData terrainData = targetTerrain.terrainData;
|
||
List<TreePrototype> existingPrototypes = new List<TreePrototype>(terrainData.treePrototypes);
|
||
|
||
int added = 0;
|
||
foreach (var prefab in treePrefabs)
|
||
{
|
||
if (prefab == null) continue;
|
||
|
||
bool alreadyExists = existingPrototypes.Exists(p => p.prefab == prefab);
|
||
if (!alreadyExists)
|
||
{
|
||
TreePrototype newProto = new TreePrototype { prefab = prefab };
|
||
existingPrototypes.Add(newProto);
|
||
added++;
|
||
}
|
||
}
|
||
|
||
terrainData.treePrototypes = existingPrototypes.ToArray();
|
||
|
||
Debug.Log($"✅ 已添加 {added} 个新树种到 Terrain!");
|
||
}
|
||
}
|