How to access the persistent data property of Grasshopper components in C#.
Say for example you want to read the value of ‘2’ which is saved internally within a ‘Num’ component.
We can look up the Num class and access the property from here quite easily. But what if we want to do it a bit more generically, so we can access the persistent data within any component?
We can do this by accessing the GH_PersistentParam(T) class. But because this class is in a different namespace/class hierarchy to the IGH_Param class (where we would normally be working to access component properties) it takes a little bit of work to manoeuvre data without Grasshopper having a small fit. (Read here for a forum post where David Rutten explains the class hierarchy behind Grasshopper.)
Two similar solutions I’ve produced today are:
var param2 = Component.Params.Input.Sources as Grasshopper.Kernel.GH_PersistentParam<Grasshopper.Kernel.Types.GH_Number>;
A = param2.PersistentData;
…and the one-line alternative:
A = ((Grasshopper.Kernel.GH_PersistentParam<Grasshopper.Kernel.Types.GH_Number>) Component.Params.Input.Sources).PersistentData;
This is a great simplification of the problem – it will only looks at the 1st component connected to the 1st input. And since PersistentData returns as GH_Structure, rather than dealing with data trees, it is easiest just to use square bracket notation to retrieve the first item (which is valid if we only have one item in our persistent data, as in this example).