key | 要检查的键的名称。 |
bool 键是否存在。
如果key
存在于首选项文件中,则返回 true。
检查首选项文件以识别指定的键是否存在。返回 true 或 false。在以下示例中,可以将键和值写入首选项文件,或将其删除。使用 HasKey 函数检查键是否存在并显示消息。
使用保存、删除和 HasKey 首选项检查。
// Small example where the XyZ key can be saved or deleted from the Preferences file. // The existence of the key is checked using the HasKey() function.
using UnityEngine; using UnityEditor;
public class HasKeyExample : EditorWindow { private string keyName = "XyZ";
[MenuItem("Examples/HasKey Example")] static void Init() { HasKeyExample window = (HasKeyExample)EditorWindow.GetWindowWithRect( typeof(HasKeyExample), new Rect(0, 0, 250, 80)); window.Show(); }
void OnGUI() { EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Save '" + keyName + "' as Key")) EditorPrefs.SetString(keyName, "abc123");
if (GUILayout.Button("Delete Key '" + keyName + "'")) EditorPrefs.DeleteKey(keyName);
EditorGUILayout.EndHorizontal();
GUILayout.Label(keyName + " key exists: " + EditorPrefs.HasKey(keyName));
if (GUILayout.Button("Close")) this.Close(); }
// delete the key each time the demo starts void OnFocus() { EditorPrefs.DeleteKey(keyName); } }