2

I'm dynamically adding controls to a dat.gui interface, but the "save settings" functionality doesn't recognize them.

var mygui = new dat.GUI();
mygui.remember(mygui);

// standard way of adding a control
mygui.control1 = 0.0;
var control = mygui.add(mygui, 'control1', -1, 1);

// adding controls dynamically
var myArray = ['control2', 'control3'];
var controls = [];
for (x in myArray) {
    controls[myArray[x]] = 0.0;
    var newControl = mygui.add(controls, myArray[x], -1, 1);
}

The controls all work as expected, but when I click the gear icon, the settings JSON only contains the first control, or any other controls I add in the normal way:

{
  "preset": "Default",
  "closed": false,
  "remembered": {
    "Default": {
      "0": {
        "control1": 0.5,
      }
    }
  },
  "folders": {}
}

I assume I'm confusing the remember() functionality somehow, any ideas?

meetar
  • 7,443
  • 8
  • 42
  • 73

1 Answers1

3

The lines in the for loop should be:

mygui[myArray[x]] = 0.0;
var newControl = mygui2.add(mygui, myArray[x], -1, 1);

The first parameter of the add function performs two functions: it is both the source of the second parameter (the name of the control to be added, which in this case is myArray[x]) but also the destination. You can store the control names wherever you like, but if the first parameter isn't the gui, the remember() function won't know about the controls, and they won't be added to the gui's __rememberedObjects attribute or saved in the JSON object.

meetar
  • 7,443
  • 8
  • 42
  • 73
  • Brilliant answer! If somebody happens to actually *want* the GUI to *not* remember a certain setting, they should additionally set `newControl.isModified = function() { return false; };` to prevent it from showing the star next to the preset name. – Mihai Todor Nov 17 '19 at 22:48