Save dat.gui presets for dynamically added control

2019-08-08 20:35发布

问题:

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?

回答1:

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.