Error when saving System.Random.

Discussion and help for Easy Save 3
Post Reply
Michal.Stangel
Posts: 10
Joined: Mon Mar 18, 2019 3:12 pm

Error when saving System.Random.

Post 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);	
}
User avatar
Joel
Moodkie Staff
Posts: 4849
Joined: Wed Nov 07, 2012 10:32 pm

Re: Error when saving System.Random.

Post 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
Joel @ Moodkie Interactive
Purchase Easy Save | Contact | Guides | Docs | Getting started
Michal.Stangel
Posts: 10
Joined: Mon Mar 18, 2019 3:12 pm

Re: Error when saving System.Random.

Post 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
Post Reply