Update Inputs after changing Number Slider - C# Component

Hi everyone

I have a C# component which have several Inputs. One of them is a Numberslider. I want the slider to randomly chose one value when running the code. The change of the number slider modifies a geometry which outputs several points which are then also a input into the C# component.

What I am trying to achieve is that after the number slider changes the value then the code to update the object with the points. Right now it is always the old points which are available for the C#-Component. I tried using ExpireSolution but I think I dont quite understand how to use it.

private void RunScript(bool Run, List<Point3d> Phenotype, double Fitness_Area, double Fitness_Ratio, double Fitness_Boarder, object Genes, int Combinations, ref object A, ref object B)
  {
    if (Run)
    {
      var input = Component.Params.Input[5].Sources[0];
      var slider = input as Grasshopper.Kernel.Special.GH_NumberSlider;

      Random random = new Random();
      int permutation = random.Next(1, Combinations);

      if (slider != null)
      {
        slider.SetSliderValue(permutation);
        //GrasshopperDocument.ScheduleSolution(10, ScheduleSolutionCallback);
      }


      A = Phenotype;
      B = permutation;
    }
  }

Hi,

If you are modifying the inputs of a component during a solution, you need to schedule a new solution and make the changes in a callback.

Here is an example :

private void RunScript(object x, List<Point3d> y, ref object A)
  {

    ghn = this.Component.Params.Input[0].Sources[0] as Grasshopper.Kernel.Special.GH_NumberSlider;

    if (ghn != null)
    {
      if (!expired)
      {
        GrasshopperDocument.ScheduleSolution(0, callback);
      }
      else
      {
        expired = false;
        //your main code here
        
        A = y;
      }
    }


  }

  // <Custom additional code> 
  public bool expired = false;
  public Grasshopper.Kernel.Special.GH_NumberSlider ghn = null;

  private void callback(GH_Document document)
  {
    Random r = new Random();
    int k = r.Next((int) Math.Ceiling(ghn.Slider.Minimum), (int) Math.Ceiling(ghn.Slider.Maximum));
    ghn.TrySetSliderValue(k);
    expired = true;
    this.Component.ExpireSolution(false);
  }

updatecomponent.gh (12.5 KB)

3 Likes

Thank you very much! Your solution works perfectly :slight_smile:

Small correction, you need to use

this.Component.ExpireSolution(true);

Otherwise, if by chance the new random slider is the same as the previous one, the component doesn’t recompute.

1 Like