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

EditorWindow.OnSelectionChange()

建议修改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交的内容,但我们确实阅读了用户提出的每项更改建议,并将根据情况进行更新。

关闭

提交失败

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

关闭

取消

描述

每当选择发生变化时调用。


保存当前选择,并通过简单点击稍后加载。

// Simple example that lets you save the current selection and load it.

using UnityEditor;
using UnityEngine.UIElements;

public class OnSelectionChangeExample : EditorWindow
{
    private int[] selectionIDs;

    [MenuItem("Examples/Selection Saver")]
    private static void Init()
    {
        OnSelectionChangeExample window = (OnSelectionChangeExample)GetWindow(typeof(OnSelectionChangeExample));
        window.Show();
    }

    void CreateGUI()
    {
        var buttonSave = new Button();
        buttonSave.text = "Save";
        buttonSave.clicked += () => SaveSelection();
        rootVisualElement.Add(buttonSave);
        
        var buttonLoad = new Button();
        buttonLoad.text = "Load";
        buttonLoad.clicked += () => LoadLastSavedSelection();
        rootVisualElement.Add(buttonLoad);

        // Initialize selectionIDs at least once
        OnSelectionChange();
    }

    void OnSelectionChange()
    {
        selectionIDs = Selection.instanceIDs;
    }

    private void SaveSelection()
    {
        var saveStr = "";

        foreach (int i in selectionIDs)
        {
            saveStr += i + ";";
        }

        saveStr = saveStr.TrimEnd(char.Parse(";"));
        EditorPrefs.SetString("SelectedIDs", saveStr);
    }

    private void LoadLastSavedSelection()
    {
        string[] strIDs = EditorPrefs.GetString("SelectedIDs").Split(char.Parse(";"));

        int[] ids = new int[strIDs.Length];
        for (var i = 0; i < strIDs.Length; i++)
        {
            if (!string.IsNullOrEmpty(strIDs[i]))
                ids[i] = int.Parse(strIDs[i]);
        }

        Selection.instanceIDs = ids;
    }
}