Recipes

# Remote config for Unity

Change a Unity game's settings, events and kill switches after release, with UnityWebRequest, typed C# from the schema, and the last good copy on disk.

Tune drop rates, run a weekend event or turn off a broken mode in a released game, without a patch or a store review. This recipe is a Unity `MonoBehaviour` that fetches a JSON file from hotcfg, decodes it into C# classes generated from the bin's schema, keeps the last good copy on disk, and never holds up the game.

## The config

game-config.json

```
{
  "motd": "Double XP this weekend!",
  "double_xp": true,
  "modes": { "ranked": true },
  "spawn_rate": 1.0
}
```

A schema keeps a typo from reaching every player. `JsonUtility` would quietly leave a misspelled or mistyped field at its default; with a schema, hotcfg refuses the push instead.

schema.json

```
{
  "type": "object",
  "required": ["double_xp", "modes", "spawn_rate"],
  "properties": {
    "motd": { "type": "string", "maxLength": 200 },
    "double_xp": { "type": "boolean" },
    "modes": { "type": "object", "additionalProperties": { "type": "boolean" } },
    "spawn_rate": { "type": "number", "minimum": 0.1, "maximum": 5 }
  }
}
```

terminal

```
hotcfg bins create game-config --schema schema.json --public
hotcfg push game-config.json --bin game-config --env production
```

## Typed C# from the schema

The generated classes use Newtonsoft.Json, which Unity ships as a package. In **Window → Package Manager → + → Add package by name**, add `com.unity.nuget.newtonsoft-json`. Then:

terminal

```
hotcfg types --bin acme/game-config --lang csharp --package Game.Config -o Assets/Scripts/GameConfig.cs
```

You get a `GameConfig` class with `DoubleXp`, `Modes`, `SpawnRate` and `Motd`, and `GameConfig.FromJson(text)`, which throws when a required field is missing or has the wrong type. Rename a key in the schema and run it again: the game stops compiling where it reads the old name, instead of breaking after release. Needs CLI 0.5.0 or later; see [hotcfg types](https://hotcfg.run/docs/cli/types).

## The loader

Put a copy of `game-config.json` in your project as the defaults the game ships with (any folder under `Assets`). Add this component to an object in your first scene and drag the file onto **Defaults** in the Inspector.

RemoteConfig.cs

```
using System;
using System.Collections;
using System.IO;
using Game.Config;
using UnityEngine;
using UnityEngine.Networking;

public class RemoteConfig : MonoBehaviour
{
    const string Url = "https://api.hotcfg.run/v1/acme/game-config";
    const int TimeoutSeconds = 2; // then the saved or bundled config stays

    [SerializeField] TextAsset defaults;

    /// <summary>The config in use: the last good copy, or the defaults.</summary>
    public static GameConfig Current { get; private set; }
    public static event Action Updated;

    static string CachePath => Path.Combine(Application.persistentDataPath, "hotcfg.json");
    string etag = "";

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        Current = GameConfig.FromJson(defaults.text);
        if (File.Exists(CachePath) && TryParse(File.ReadAllText(CachePath), out var saved))
        {
            Current = saved;
            etag = PlayerPrefs.GetString("hotcfg.etag", "");
        }
        Refresh();
    }

    /// <summary>Fetches the latest config. Call it again when the player returns to the menu.</summary>
    public void Refresh() => StartCoroutine(Fetch());

    IEnumerator Fetch()
    {
        using var req = UnityWebRequest.Get(Url);
        req.timeout = TimeoutSeconds;
        if (etag != "") req.SetRequestHeader("If-None-Match", etag);
        yield return req.SendWebRequest();

        // Offline, timed out, unchanged (304) or an error: keep what we have.
        if (req.result != UnityWebRequest.Result.Success || req.responseCode != 200) yield break;

        var text = req.downloadHandler.text;
        if (!TryParse(text, out var next)) yield break; // unexpected shape: keep what we have

        Current = next;
        etag = req.GetResponseHeader("ETag") ?? "";
        File.WriteAllText(CachePath, text);
        PlayerPrefs.SetString("hotcfg.etag", etag);
        Updated?.Invoke();
    }

    static bool TryParse(string text, out GameConfig config)
    {
        try
        {
            config = GameConfig.FromJson(text);
            return true;
        }
        catch (Newtonsoft.Json.JsonException)
        {
            config = null;
            return false;
        }
    }
}
```

Read values anywhere, and react when new ones arrive:

MainMenu.cs

```
using UnityEngine;
using UnityEngine.UI;

public class MainMenu : MonoBehaviour
{
    [SerializeField] Text motd;
    [SerializeField] Button ranked;

    void OnEnable() { RemoteConfig.Updated += Apply; Apply(); }
    void OnDisable() => RemoteConfig.Updated -= Apply;

    void Apply()
    {
        var c = RemoteConfig.Current;
        motd.text = c.Motd ?? "";
        ranked.interactable = !c.Modes.TryGetValue("ranked", out var on) || on;
    }
}
```

## IL2CPP builds

At higher **Managed Stripping Level** settings, Unity can strip the setters that Newtonsoft.Json fills. If values come back empty in a player build but not in the Editor, keep the generated types with an `Assets/link.xml`:

link.xml

```
<linker>
  <assembly fullname="Assembly-CSharp">
    <namespace fullname="Game.Config" preserve="all"/>
  </assembly>
</linker>
```

## Notes

- **The game never waits:** the first frame uses the saved copy or the bundled defaults. A new config applies when it arrives, through `Updated`; apply it on the next screen if you'd rather not change things mid-match.
- **Validation:** the schema stops bad config at push time. `FromJson` is the second line of defence on the device, for a saved file damaged on disk: it throws, and the loader keeps what it had.
- **Private bins:** read from `https://private-api.hotcfg.run` instead, and add `req.SetRequestHeader("Authorization", "Bearer pk_live_…");` with a publishable key limited to that bin. A key shipped in a game can be extracted, so keep secrets out of config either way. See [Reading a bin](https://hotcfg.run/docs/reference/reading#private-bins).
- **WebGL builds:** hotcfg answers reads from any site (public bins, and private bins with a publishable key), so the request works from a browser too.
- **Testing failures:** point `Url` at `?status=503` or `?delay=5000` to check that the game still starts on its saved copy. See [Testing slow and failing networks](https://hotcfg.run/docs/guides/testing-failures).
- **Per-version settings:** to change a value only for old builds of the game, see [version targeting](https://hotcfg.run/docs/recipes/version-targeting).
- **Events on a schedule:** test the event's config in staging, then [schedule the promote](https://hotcfg.run/docs/guides/scheduling) for when it starts, with a revert for when it ends: `hotcfg promote game-config --from staging --to production --at 2026-11-21T18:00:00Z --revert-at 2026-11-24T06:00:00Z`.

Last updated 17 November 2026
