版本:Unity 6 (6000.0)
语言英语
  • C#

EditorWindow.OnInspectorUpdate()

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法采纳所有提交,但我们确实阅读了用户提出的每一项更改建议,并在适用的情况下进行更新。

关闭

提交失败

由于某些原因,您的更改建议无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

描述

OnInspectorUpdate 每秒调用 10 次,以便检查器有机会更新。

// Simple script that aligns the position of several selected GameObjects
// with the first selected one.

using UnityEditor;
using UnityEngine;
using System.Collections;
using UnityEngine.UIElements;

public class OnInspectorUpdateExample : EditorWindow
{
    bool alignToX = true;
    bool alignToY = true;
    bool alignToZ = true;
    string selected = "";
    string alignTo = "";

    [MenuItem("Examples/OnInspectorUpdate example")]
    static void Init()
    {
        OnInspectorUpdateExample window = (OnInspectorUpdateExample)GetWindow(typeof(OnInspectorUpdateExample));
        window.Show();
    }

    void  OnInspectorUpdate()
    {        
        selected = Selection.activeTransform ? Selection.activeTransform.name : "";
    }

    void CreateGUI()
    {
        var label = new Label("Select various Objects in the Hierarchy view to align them with the first selected one.");
        rootVisualElement.Add(label);

        selected = Selection.activeTransform ? Selection.activeTransform.name : "";

        var labelSelected = new Label();
        rootVisualElement.Add(labelSelected);

        labelSelected.schedule.Execute(() =>
        {
            labelSelected.text = $"Selected object: {selected}";
        }).Every(10);

        var toggleX = new Toggle();
        toggleX.text = "X";
        toggleX.value = alignToX;
        toggleX.RegisterValueChangedCallback(evt => alignToX = evt.newValue);
        rootVisualElement.Add(toggleX);

        var toggleY = new Toggle();
        toggleY.text = "Y";
        toggleY.value = alignToY;
        toggleY.RegisterValueChangedCallback(evt => alignToY = evt.newValue);
        rootVisualElement.Add(toggleY);

        var toggleZ = new Toggle();
        toggleZ.text = "Z";
        toggleZ.value = alignToZ;
        toggleZ.RegisterValueChangedCallback(evt => alignToZ = evt.newValue);
        rootVisualElement.Add(toggleZ);

        var buttonAlign = new Button();
        buttonAlign.text = "Align";
        buttonAlign.clicked += () => Align();
        rootVisualElement.Add(buttonAlign);
    }

    void Align()
    {
        if (selected == "")
        {
            Debug.LogError("No objects selected to align");
        }

        foreach (Transform t in Selection.transforms)
        {
            Vector3 alignementPosition = Selection.activeTransform.position;
            Vector3 newPosition;

            newPosition.x = alignToX ? alignementPosition.x : t.position.x;
            newPosition.y = alignToY ? alignementPosition.y : t.position.y;
            newPosition.z = alignToZ ? alignementPosition.z : t.position.z;

            t.position = newPosition;
        }
    }
}