-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathRebindSaveLoad.cs
More file actions
80 lines (66 loc) · 2.59 KB
/
RebindSaveLoad.cs
File metadata and controls
80 lines (66 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using UnityEngine;
using UnityEngine.InputSystem;
namespace UnityEngine.InputSystem.Samples.RebindUI
{
/// <summary>
/// Handles persisting binding overrides which implies that customizations of controls will be persisted
/// between runs.
/// </summary>
public class RebindSaveLoad : MonoBehaviour
{
[Tooltip("The associated input action asset to be serialized to player preferences (Required).")]
public InputActionAsset actions;
[Tooltip("The player preference key to be used when serializing binding overrides to player preferences (Required).")]
public string playerPreferenceKey;
[Tooltip("Specifies whether to load and apply binding overrides when the component is enabled")]
public bool loadOnEnable = true;
[Tooltip("Specifies whether to save binding overrides when the component is disabled")]
public bool saveOnDisable = true;
/// <summary>
/// Loads binding overrides from player preferences and applies them to the associated input action asset.
/// </summary>
public void Load()
{
if (!IsValidConfiguration())
return;
var rebinds = PlayerPrefs.GetString(playerPreferenceKey);
if (string.IsNullOrEmpty(rebinds))
return; // OK, we may not have saved any binding overrides yet.
actions.LoadBindingOverridesFromJson(rebinds);
}
/// <summary>
/// Saves binding overrides from the associated input action asset and persists them to player preferences.
/// </summary>
public void Save()
{
if (!IsValidConfiguration())
return;
var rebinds = actions.SaveBindingOverridesAsJson();
PlayerPrefs.SetString(playerPreferenceKey, rebinds);
}
private void OnEnable()
{
if (loadOnEnable)
Load();
}
private void OnDisable()
{
if (saveOnDisable)
Save();
}
private bool IsValidConfiguration()
{
if (actions == null)
{
Debug.LogWarning("Unable to apply binding overrides from player preferences without an associated action asset.");
return false;
}
if (string.IsNullOrEmpty(playerPreferenceKey))
{
Debug.LogWarning("Unable to load binding overrides from player preferences without a non-empty preference key.");
return false;
}
return true;
}
}
}