Why is .plugTo() not setting the initial value with ControlP5?

Hi!

I’m using the controlP5 library to change variables inside an object. I use .plugTo() to specify which object contains the variables to control.

The issue is that the slider always shows 0 when the program starts, even if cfg.opacity is not 0. Calling .setValue(160) or .update() makes no difference, it still shows 0 when the program starts.

import controlP5.*;

ControlP5 cp5;
Config cfg;

class Config {
  int opacity = 160;
}

void setup() {
  size(200, 100);
  cfg = new Config();
  cp5 = new ControlP5(this);
  println(cfg.opacity); // prints 160
  cp5.addSlider("opacity")
    .plugTo(cfg)
    .setRange(0, 255)
    //.setValue(cfg.opacity) // does not help
    //.update() // does not help
    ;
}
void draw() {
}
void mouseReleased() {
  println(cfg.opacity);
}

I know the value IS connected to the object because if I change the slider and I quit the app, the right value gets saved to disk. It’s just that when I start it again it shows 0.

Any hacks around this?

Very weird. I found a workaround:

  float v = cfg.opacity;
  s = cp5.addSlider("opacity")
    .plugTo(cfg)
    .setRange(0, 255)
    .setValue(v)
    ;

So if I store the object property in a temporary variable it does work… ???

I think ControlP5 only mutates fields by reflection. :thinking:
But it never does the opposite. That is, it never reads fields. :disappointed:
Therefore, if we manually change a “plugged” field, ControlP5 will never realize it. :flushed:

Good to know, thank you :slight_smile: But why does it not work to .setValue(cfg.opacity)? There I’m directly specifying the value but it sees that value as 0. If I set it to .setValue(cfg.opacity + 5) the slider shows 5. Very odd.

B/c apparently plugTo() mutates the plugged field right way: :open_mouth:

  println(cfg.opacity); // prints 160

  cp5.addSlider("opacity")
    .plugTo(cfg)
    .setRange(0, 255)
    .setValue(cfg.opacity)
    ;

  println(cfg.opacity); // prints 0

As a workaround, invoke plugTo() after setValue(): :smile_cat:

  println(cfg.opacity); // prints 160

  cp5.addSlider("opacity")
    .setRange(0, 255)
    .setValue(cfg.opacity)
    .plugTo(cfg)
    ;

  println(cfg.opacity); // prints 160

Ah I used to know this! Thanks for find it :slight_smile:

So intuitive! :crazy_face:

I opened an issue in GitHub,