gpt4 book ai didi

unity3d - 防止 Unity Editor 应用程序进入播放模式

转载 作者:行者123 更新时间:2023-12-04 01:49:28 25 4
gpt4 key购买 nike

是否可以防止 Unity 在用户按下按钮后更改播放模式?

假设我有一个自定义编辑器,它的状态可能无法正确序列化;如果此时用户更改 Unity Editor 模式,他们的更改将会丢失。

完全摆脱不可序列化状态是一种选择,但这是完全不同复杂度的任务。想避免这种情况。

更新:

我测试了derHugo's answer使用以下脚本:

using UnityEditor;
using UnityEngine;

namespace Innoactive.Hub.Training.Editors
{
[InitializeOnLoad]
public class ProveThatDudeWrongWindow : EditorWindow
{
private static ProveThatDudeWrongWindow windowInstance;

private string notSerializedString = "default";

static ProveThatDudeWrongWindow()
{
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}

[MenuItem("Test/I'm damn sure he's wrong")]
private static void MenuItem()
{
if (windowInstance == null)
{
windowInstance = GetWindow<ProveThatDudeWrongWindow>();
}

windowInstance.notSerializedString = "some value";
}

[MenuItem("Test/Display current value")]
private static void DisplayCurrentNonSerializedValue()
{
windowInstance = GetWindow<ProveThatDudeWrongWindow>();
Debug.Log("string: " + windowInstance.notSerializedString);
}

private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
{
EditorApplication.isPlaying = false;
}

Debug.Log("state: " + state);
}
}
}

然后我做了以下事情:

  1. Test/I'm damn sure he's wrong 选项将非序列化值从 default 值设置为 some value
  2. 测试/显示当前值以确保值已更改
  3. 按播放键
  4. 测试/显示当前值查看当前值。如果它是default,derHugo 的解决方案不起作用,如果它是some value,它就起作用。

结果:derHugo 很酷。

最佳答案

是的,我想

您可以注册到EditorApplication.playModeStateChanged

看我修改过的文档中的例子:

using UnityEngine;
using UnityEditor;

public static class PlayModeStateChangedExample
{
private static void LogPlayModeState(PlayModeStateChange state)
{
Debug.Log(state);
}

public static void SetPlayModeEnabled(bool enabled)
{
//This is possible since you allways can remove
//a listener even if there is none so far
//This allways removes the listener making sure it is only added once
EditorApplication.playModeStateChanged -= LogPlayModeState;

if(!enabled)
{
EditorApplication.playModeStateChanged += LogPlayModeState;
}
}
}

现在剩下的就是重置EditorApplication.isPlaying回到 false 例如通过替换

Debug.Log(state);

// This mode occures right before entering PlayMode
// and is the moment in which we want to intervene
if(state == PlayModeStateChange.ExitingEditMode)
{
EditorApplication.isPlaying = false;
}

终止 PlayMode。

这样你就可以从任何地方打电话,例如

PlayModeStateChangedExample.SetPlayModeEnabled(false);

但是我不确定这是否会完全阻止序列化部分,因为它也在文档中说明

Setting isPlaying delays the result until after all script code has completed for this frame.

关于unity3d - 防止 Unity Editor 应用程序进入播放模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53921529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com