在Unity中创建自定义编辑器窗口时,我有多个类型的变量(枚举,布尔值,整数,字符串等(以及一个输入字段。当然,当您输入值时,当您重新启动 Unity 时,它们会被遗忘。因此,为了解决这个问题,我创建了一个额外的类来保存这些值。
这适用于所有类型(布尔值、整数、字符串、枚举等(,但我不知道如何保存 Unity 组件(例如 InputField(的赋值。
下面是我创建的代码,所有这些代码都可以工作,但是当我重新启动 Unity 时,我需要找到一种方法让工具不要忘记从 inputField 中的层次结构分配的对象。
public class Tool : EditorWindow
{
public InputField inputField;
private bool myBool = true;
private string myString = "Hello World";
public void OnGUI()
{
inputField = (InputField)EditorGUILayout.ObjectField("Input Field", inputField, typeof(InputField), true);
GetRestApiMain.myBool = EditorGUILayout.Toggle("Bool", GetRestApiMain.myBool );
GetRestApiMain.myString = EditorGUILayout.TextField("Hello World", GetRestApiMain.myString);
}
}
public class ToolReferences
{
/* public static InputField inputField ?
* {
* I don't know what to do here to save the InputField set by the user
* All the below works, and want to have the same for InputField
* whereby the assignment is not forgotten on restart.
* } */
public static bool myBool
{
get
{
#if UNITY_EDITOR
return EditorPrefs.GetBool("Bool", false);
#else
return false;
#endif
}
set
{
#if UNITY_EDITOR
EditorPrefs.SetBool("Bool", value);
#endif
}
}
public static string myString
{
get
{
#if UNITY_EDITOR
return EditorPrefs.GetString("Hello World", "");
#else
return false;
#endif
}
set
{
#if UNITY_EDITOR
EditorPrefs.SetString("Hello World", value);
#endif
}
}
}
解决方案是在主类中获取OnGUI();
对象的实例ID。然后将 ID 存储在另一个类的静态 int 中,而不是static InputField
中。下面是工作代码。 (感谢@milan-egon-votrubec 的 InstanceID 指针(
在将 int 设置为0
之前,这不会让您删除分配,但您可以替换它,它会在重新启动后保存。我相信有更好的解决方案,但就目前而言,这在多个场景中进行测试后有效,在单个场景中没有错误。如果您更改场景,它将失去其分配,除非您使用预制件。
工具引用类...
// class ToolReferences
public static int inputFieldId
{
get
{
#if UNITY_EDITOR
return EditorPrefs.GetInt("inputFieldId", 0);
#else
return false;
#endif
}
set
{
#if UNITY_EDITOR
EditorPrefs.SetInt("inputFieldId", value);
#endif
}
}
然后在工具类中...
public class Tool : EditorWindow
{
public InputField inputField;
// ...
public void OnGUI()
{
inputField = (InputField)EditorGUILayout.ObjectField("Input Field", inputField, typeof(InputField), true);
// if inputField has nothing currently assigned
if (inputField == null)
{
// make sure we have and int stored
if (ToolReferences.inputFieldId != 0)
{
inputField = (InputField)EditorUtility.InstanceIDToObject(ToolReferences.inputFieldId);
}
else // ... prompt the user to assign one
}
// if we have an InputField assigned, store ID to int
else if (inputField != null) ToolReferences.inputFieldId = inputField.GetInstanceID();
}
}
// ...
}
您可以通过传入 InputField 实例将 InputFieldInstanceID
保存到EditorPrefs
,然后反向检索它:
public static InputField GetInputField
{
get
{
return EditorUtility.InstanceIDToObject(EditorPrefs.GetInt("InputFieldId"));
}
set
{
EditorPrefs.GetInt("InputFieldId", value.GetInstanceID());
}
}