How to add userobject to gh ToolPanel by C#?

i am trying to add a userobject component to toolPanel,but failed,this is my try:
this is userobject:
image
i drag it into visualstudio,and it become a byte:
image

But I have to stop now,because I donnot know how to add this userobject to toolpanel when the grasshopper is starting with other my custom c# component is loading…
image
(for example:add the userobject(in byte) in such a place automaticlly when loading)
do some one have idea about it?
Thank you very much!

    string target = Grasshopper.Folders.DefaultUserObjectFolder + "MyUserObject.ghuser";
    if (!System.IO.File.Exists(target))
    {
      byte[] bytes = get your byte array out of the resources...
      System.IO.File.WriteAllBytes(target, bytes);
    }
1 Like

Thank you David,it works!
But,how to run your code at everytime my “.gha” is loading?
Thank you!

You can create a Grasshopper.Kernel.GH_AssemblyPriority object in your plugin which will be once whenever the plugin is loaded. I’m not entirely sure what will happen when you start populating the UserObject folder during load, there may be awkward race conditions there. You may want to delay the actual writing of the files until the Grasshopper.Instances.CanvasCreated or Grasshopper.Instances.DocumentServer.DocumentAdded events fire.

Thankyou David!
i put add handle method to event in PriorityLoad:


(and handle method is in a static class: “Common”.)
it works well ,but is PriorityLoad the good place to put
“Grasshopper.Instances.CanvasCreated += Common.CreateUserObject;” ?or other place better?
Thank you!

Yep, it’s a good place. It only won’t work if your plugin is loaded after Grasshopper loads. So if Common.CreateUserObject is cheap to call, you could even put it into the constructor of one of your components.

Thank you David!

David,if i delet or add “ghuser” in DefaultUserObjecFolder,the userObjectl will be immediately appear or disappear in the tool panel.
But if i add a fold in DefaultUserObjecFolder,for example:
image
When delete or add the object in “jj” folder,it will not be appear or disappear by restart Grasshopper rather than immdiately…
Do you have some idea of this ?because i prefere make it immediate to show…not restart gh.
Thank you

Hi there,

I realize this is an old thread, but did you ever find a way to live load user objects from sub-folders? I’m encountering the same issue now.