您可以添加一个自定义窗口编辑器,OnHierarchyChange
用于处理层次结构窗口中的所有更改。此脚本必须位于Editor文件夹中。要使其自动工作,请确保首先打开此窗口。
using System.Linq;
using UnityEditor;
using UnityEngine;
public class HierarchyMonitorWindow : EditorWindow
{
[MenuItem("Window/Hierarchy Monitor")]
static void CreateWindow()
{
EditorWindow.GetWindow<HierarchyMonitorWindow>();
}
void OnHierarchyChange()
{
var addedObjects = Resources.FindObjectsOfTypeAll<MyScript>()
.Where(x => x.isAdded < 2);
foreach (var item in addedObjects)
{
//if (item.isAdded == 0) early setup
if (item.isAdded == 1) {
// do setup here,
// will happen just after user releases mouse
// will only happen once
Vector3 p = transform.position;
item.transform.position = new Vector3(p.x, 2f, p.z);
}
// finish with this:
item.isAdded++;
}
}
}
我将以下脚本附加到框中:
public class MyScript : MonoBehaviour {
public int isAdded { get; set; }
}
请注意,它OnHierarchyChange
被调用了两次(一次是当您开始将框拖到场景上时,一次是当您释放鼠标按钮时),因此isAdded
被定义为 anint
以使其能够与2
. 所以你也可以有初始化逻辑x.isAdded < 1