Saving user bindings

There’s no API yet to assist directly in persisting bindings. It’s something we’d like to take a look at after 1.0. An overall sample for a rebinding screen has landed and should be in the next package.

For persisting binding customizations, you can traverse of the set of bindings in each action map using InputActionMap.bindings and for each one that has an overridePath set, save it along with the ID of the binding. When loading, you can look up the bindings by ID and put the override back in place.

// Saving.
var overrides = new Dictionary<Guid, string>();
foreach (var map in asset.actionMaps)
    foreach (var binding in map.bindings)
    {
        if (!string.IsNullOrEmpty(binding.overridePath))
            overrides[binding.id] = binding.overridePath;
    }

// Loading.
foreach (var map in asset.actionMaps)
{
    var bindings = map.bindings;
    for (var i = 0; i < bindings.Count; ++i)
    {
        if (overrides.TryGetValue(bindings[i].id, out var overridePath)
            map.ApplyBindingOverride(i, new InputBinding { overridePath = overridePath });
    }
}

There’ll be a more elegant API for this later on. What I think would be great to have would be a simple API that just returns a string in JSON format that you can store anywhere and that you can then hand back to the API and it restores all overrides for you.

15 Likes