在Unity中创建自定义EditorWindow时,我有多种类型的变量(枚举、布尔、整数、字符串等)以及InputField。当然,当您输入值时,当您重新启动Unity时,它们会被忘记。所以为了解决这个问题,我创建了一个额外的类来保存这些值。
这适用于所有类型(bools、int、string、enum等),但我不知道如何保存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
}
}
}
发布于 2018-06-21 00:58:43
解决这个问题的方法是在主类中获取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();
}
}
// ...
}
发布于 2018-06-18 14:27:21
您可以将InputField InstanceID
保存到EditorPrefs
,方法是传入InputField实例,然后反向检索它:
public static InputField GetInputField
{
get
{
return EditorUtility.InstanceIDToObject(EditorPrefs.GetInt("InputFieldId"));
}
set
{
EditorPrefs.GetInt("InputFieldId", value.GetInstanceID());
}
}
https://stackoverflow.com/questions/50902535
复制相似问题