我试图做一个自定义的统一编辑,由于某种原因,每次我关闭窗口,然后再次打开它的时候,我的列表重置为空。
我试图通过键和值分成2个独立的名单OnDisable
数据从字典中保存,然后重新创建相结合,列出了字典OnEnable
。但每次OnEnable
叫我从我的列表中得到一个空...
下面是代码是什么样子的例子。
public Dictionary<string, string> myDictionary = new Dictionary<string, string>();
[SerializeField]
public List<string> listOfDictionaryKeys;
private void OnEnable()
{
// this always returns null
Debug.Log(listOfDictionaryKeys.Count);
}
private void OnDisable()
{
// this successfully saves the keys to the list
listOfDictionaryKeys = (myDictionary.Keys).ToList();
}
没有人有任何想法,为什么我可能会失去我的列表数据?我不是在检查器中设置的任何值,他们都被设置,并通过代码保存。
UnityEditor是(伟大的工具)棘手的野兽,运行其自己的回调循环,并在编辑器中系列化和deserialisation可有点凌乱。
有时候,团结将igoner无论一个物体的构造做了,并用默认值覆盖它,在下次更新。我想,当其中一个列表有望找到空对象的检查初始化它,但如果你不保存新的序列化形式与您的场景,它仍将是空的,当OnEnable发生在bulld将为空(deserialisation之后),除非其保存现场。
我没有过程的充分掌握,但是这就是我的想象。
对于一个快速的解决方法做:
private void OnEnable()
{
if (listOfDictionaryKeys==null) listOfDictionaryKeys=new List<string>();
// this always returns null
Debug.Log(listOfDictionaryKeys.Count);
}
这样一来,你会不小心删除它的情况下,它的存在
我真的不从你的问题理解OnEnable
和OnDisable
是否是你的编辑脚本或组件本身的一部分。
如果以后:
当组件从禁用变为启用状态OnEnable
被调用,不是在它获得焦点的检查。以同样的方式OnDisabled
被称为当组件或根据游戏物体被禁用,未如果它失去焦点。
如果你想要的是反应在检查获得和失去焦点是什么必须是OnEnable
和OnDisable
督察脚本本身。例如。
[CustomEditor(typeof(XY)]
public class XYEditor : Editor
{
XY _target;
SerializedProperty list;
// Called when the class gains focus
private void OnEnable()
{
_target = (XY) target;
//Link the SerializedProperty
list = serializedObject.FindProperty("listOfDictionaryKeys");
}
public override void OnInpectorGUI()
{
//whatever your inspector does
}
// Called when the component looses focus
private void OnDisable()
{
serializedObjet.Update();
// empty list
list.ClearArray;
// Reading access to the target's fields is okey
// as long as you are sure they are set at the moment the editor is closed
foreach(var key in _target.myDoctionary.keys)
{
list.AddArrayElementAtIndex(list.arraySize);
var element = list.GetArrayElementAtIndex(list.arraySize - 1);
element.stringValue = key;
}
serialzedObject.ApplyModifiedProperties;
}
}
我还没有看到你填充字典那里,因为你说这是不是在检查发生。这可能是当mixonbSerializedProperty
直接访问领域的问题。