Version: 2017.1
public static bool HasKey (string key);

参数

key 要检查的键的名称。

返回

bool 键是否存在。

描述

如果偏好设置文件中存在 /key/,则返回 true。

检查偏好设置文件,以确定指定的键 是否存在。可能会返回 true 或 false。在以下示例中,可以将键和值 写入偏好设置文件,也可以将其删除。 使用 HasKey 函数检查键是否存在,并显示一条消息。


“使用 Save、Delete 和 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); } }