A number slider in Grasshopper, automatically created with a Grasshopper C# script

Instantiate new Grasshopper objects automatically with C#

The code here is doing two things:

  • Creating a new slider automatically and positioning it on the canvas
  • Connecting this slider to the original component

This is possible with any Grasshopper object, assuming you can find the class necessary to instantiate the component you are interested in.

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

    Random rnd = new Random();

    if(x)
    {
      //instantiate  new slider
      Grasshopper.Kernel.Special.GH_NumberSlider slid = new Grasshopper.Kernel.Special.GH_NumberSlider();
      slid.CreateAttributes(); //sets up default values, and makes sure your slider doesn't crash rhino
      
      //customise slider (position, ranges etc)
      int inputcount = this.Component.Params.Input[1].SourceCount;
      slid.Attributes.Pivot = new PointF((float) this.Component.Attributes.DocObject.Attributes.Bounds.Left - slid.Attributes.Bounds.Width - 30, (float) this.Component.Params.Input[1].Attributes.Bounds.Y + inputcount * 30);
      slid.Slider.Maximum = 10;
      slid.Slider.Minimum = 0;
      slid.Slider.DecimalPlaces = 2;
      slid.SetSliderValue((decimal) (rnd.Next(1000) * 0.01));
      
      //Until now, the slider is a hypothetical object.
      // This command makes it 'real' and adds it to the canvas.
      GrasshopperDocument.AddObject(slid, false);

      //Connect the new slider to this component
      this.Component.Params.Input[1].AddSource(slid);
    }

  }

Thanks to Nicolas Chaulet who uncovered a lot of the code above.

3 thoughts on “Instantiate new Grasshopper objects automatically with C#”

  1. Thank you for sharing this helpful script–works like a charm. Is it possible to do the same in python script? I have tried accessing the Grasshopper Document and any functions to “Add” the slider, but am unable to do so. Any help would be most greatly appreciated!

  2. Hi Tracy, thanks for your comment, glad to have helped! Unfortunately I rarely use Python so won’t be able to help much. Are you importing Grasshopper libraries into your script? I would recommend installing and looking through the code of Ladybug for Grasshopper – it’s a very extensive and well-developed collection of tools written entirely in Python, and so contains many examples on how to ‘do’ Python in Grasshopper.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.