Instantiate New Object (add custom component into the canvas)

You should always use Emit if you do not necessarily know what type of object you’re creating. If the object was defined by a Python assembly then you are not allowed to construct it yourself. If however you know for a fact that the object is defined in a standard .NET assembly, then constructing it manually should be fine.

GH_Canvas.InstantiateNewObject() doesn’t necessarily just create a single object, it may choose to insert more (although at the moment it only does that for jump objects).

The key steps taken by InstantiateNewObject() are:

  • Ensure the attributes exist: if (obj.Attributes == null) obj.CreateAttributes();
  • In the case of CentralSettings.CanvasFullNames being true, it will replace all nicknames with all names in the entire attribute tree.
  • Assign the init_code if the code is not empty and the target object supports it.
  • Set the attributes pivot to (0,0), expire the layout and perform the layout:
    obj.Attributes.Pivot = new PointF();
    obj.Attributes.ExpireLayout();
    obj.Attributes.PerformLayout();
  • Use the attribute Bounds to figure out the exact position of the pivot so that the object is centred at the insertion coordinate. I.e. set pivot again, expire layout again.
  • Update the Markov chain database. If you’re auto-inserting components you probably don’t want to do this anyway.
  • If the canvas doesn’t have a document yet, create a new one.
  • Trigger an autosave on the document: Document.AutoSave(GH_AutoSaveTrigger.object_added);
  • Insert the object: Document.AddObject(obj, false);
  • Add an undo record: Document.UndoUtil.RecordAddObjectEvent("Add " + obj.Name, obj);
  • Trigger a new solution: Document.NewSolution(false);

All of the above in a try…catch block of course.

It will always add the object to the topmost index in the stack, so you can safely get the last object out of the document if you need the instance. Just do it right away, before the z-order can be changed.

About init codes: they are strings that can be assigned to object when constructing them via the double-click-type popup on the canvas. For example:

The Curve Offset component knows how to deal with the “2.5” init code string, i.e. it will parse it as a number and assign it to the Offset Distance input.

1 Like