Maya MPxNode attribute value changes after plugin reload - How to persist custom attribute values?

I have a custom Maya plugin node with an MFnNumericAttribute attribute. However, the attribute value keeps changing to a new value every time the plugin is reloaded

// In initialize()

MStatus initialize()
{
	MFnNumericAttribute numAttr;

	idAttr = numAttr.create("id", "i", MFnNumericData::kInt);
	numAttr.setWritable(false);
	numAttr.setReadable(false);
	numAttr.setStorable(true);

	addAttribute(idAttr);

	return MS::kSuccess;
}

// In postConstructor()

void postConstructor()
{
    MPlug plug(thisMObject(), idAttr);
    plug.setValue(123);
}

Steps to Reproduce:

  1. Create a scene and add my custom node ( id attribute = 123)

  2. Save the scene

  3. Open a new/empty scene

  4. Unload the plugin

  5. Reopen the original scene (Maya auto-loads the plugin)

  6. Result: The id attribute has changed to a new value (e.g., 566) instead of keeping 123

is there a reason why you set the data to 123 in the post constructor insteaf of using a default value?
the post constructor only gets called when the node is created not when its loaded from file (as far as i know)
there might be an issue with your node not having its attribute writable, which might break part of your setup as it does not know that its an input plug or how it affects that outcome of your plugin

is the idAttr an mobject that is static persistent? it might be that the mobject order gets changed on load if you dont do that and it gets arbitrary data added in.

Yeah, I actually tried setting the value as a default value,

but I ran into another issue.
The id is generated using a function that returns a random number,

and from what I noticed during testing — if the plugin isn’t loaded and then gets loaded again, Maya recreates the node and calls initialize() again.

That means the random function runs again, and the node ends up getting a new random ID each time the plugin loads.

As for the attribute, I didn’t make it writable because I don’t really need to write to it or connect anything to it later.

And yes, the idAttr is static.

Is there a reason you need to generate the unique id through the c++ node? It seems to me like you are trying to do something that is not possible or just in a very roundabout way.

If you make the id writable and storable with a default of 0, check in the init if the value is 0 → assign a unique id. If it has a different value, keep it as is. Get it working with the usual steps and after that you can check if you can make writeable False.