Page 1 of 1

Error when saving System.Random.

Posted: Mon Jan 10, 2022 4:00 pm
by Michal.Stangel
Hello,
after upgrade to Unity 2021.2.7 I am getting this error (using latest version of Easy Save 3.4.0):
MissingMemberException: A private field named inext does not exist in the type System.Random

It happens when I call:

Code: Select all

ES3.Save<System.Random>(...
And this is the problematic method in ES3Writer class. It throws error inside WritePrivateField.

Code: Select all

protected override void WriteObject(object obj, ES3Writer writer)
{
	var instance = (System.Random)obj;
			
	writer.WritePrivateField("inext", instance);
	writer.WritePrivateField("inextp", instance);
	writer.WritePrivateField("SeedArray", instance);	
}

Re: Error when saving System.Random.

Posted: Mon Jan 10, 2022 6:23 pm
by Joel
Hi there,

Thanks for bringing this to our attention. It looks like Unity have changed their implementation of Random so that it is no longer the same as .NET's implementation and is no longer serializable. Unfortunately this means we will need to drop support for this.

The only workaround would be to create a child class of Random which is serializable and use this instead of System.Random. For example:

Code: Select all

public class RandomSerializable : System.Random
{
	public int iteration = 0;
	public int seed = 0;

	bool initialised = false;
	
	public RandomSerializable(int seed) : base(seed)
	{
		this.seed = seed;
	}
	
	public RandomSerialzable() : base()
	{}
	
	public override int Next()
	{
		if(!initialised)
			for(int i=0; i<iteration; i++)
				base.Next();
		iteration++;
		return base.Next();
	}
}
All the best,
Joel

Re: Error when saving System.Random.

Posted: Tue Jan 11, 2022 8:07 am
by Michal.Stangel
Thanks Joel.

I guess UnityEngine.Random cannot be saved either. I think that's why I opted for System.Random some time ago.
I'll probably not use this workaround as my game is producing huge amount of random numbers and iterate through milions or bilions to restore the state seems scary :-)

I'll probably try this, somebody made his own Random implementation:
https://stackoverflow.com/questions/19 ... ator-in-c


https://pastebin.com/pxTvHJWL