在Unity中制作自定义EditorWindow时,我有多种类型的变量(枚举,bool,整数,字符串等)以及一个InputField。当然,当您输入值时,重启Unity时会忘记它们。所以为了解决这个问题,我创建了一个额外的类来保存这些值。
这适用于所有类型(bool,整数,字符串,枚举等),但我不知道如何为诸如InputField之类的统一组件保存赋值。
下面是我创建的代码,所有代码都有效,但是当我重新启动Unity时,我需要找到一种方法让工具不要忘记在inputField中从Hierarchy分配的对象。 < / p>
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
}
}
}
答案 0 :(得分:1)
解决方案是在主类的OnGUI();
中获取对象的InstanceID。然后将ID存储在另一个类的静态int中,而不是static InputField
中。以下是工作代码。
(感谢@ milan-egon-votrubec提供的InstanceID指针)
在将int设置为0
之前,这不会删除您的分配,但是您可以替换它,并且它将在重新启动后保存。我敢肯定有更好的解决方案,但是目前,在多种场景下测试后,在单个场景中没有错误,此方法仍然有效。如果更改场景,除非使用预制件,否则它将丢失其分配。
ToolReferences类...
// 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();
}
}
// ...
}
答案 1 :(得分:0)
您可以通过传入InputField实例将InputField InstanceID
保存到EditorPrefs
,然后反向检索它:
public static InputField GetInputField
{
get
{
return EditorUtility.InstanceIDToObject(EditorPrefs.GetInt("InputFieldId"));
}
set
{
EditorPrefs.GetInt("InputFieldId", value.GetInstanceID());
}
}