Way to preserve non-Unity.Object references?

Discussion and help for Easy Save 3
Post Reply
Posts: 6
Joined: Wed Jul 06, 2022 5:52 am

Way to preserve non-Unity.Object references?

Post by BFA »

Hi, so Class A holds a reference to an instance of Class B.

We have multiple instances of Class A that all reference the same instance of Class B.

However, when we save and load, each instance of Class A now references a unique instance of Class B (loading seems to create a new instance of Class B for each reference, resulting in many instances of Class B instead of just the single instance that existed when the game was saved).

Is there a way/best practice around this?

User avatar
Moodkie Staff
Posts: 4198
Joined: Wed Nov 07, 2012 10:32 pm

Re: Way to preserve non-Unity.Object references?

Post by Joel »

Hi there,

In this case you would need to create your own way of referencing them, as there would be no way for Easy Save to know which reference ID relates to which object between sessions.

In this case you would need to make your own way of uniquely identifying each class, for example by adding a field containing a unique ID, perhaps generated using System.Guid.NewGuid().ToString(). Whenever you create a new class, add it to a Dictionary<string, YourClass> which will allow you to lookup your classes. Before saving anything, you would then save this Dictionary.

Then before loading anything, you would load this Dictionary. Whenever you load a reference to your class, you should check whether a class with that reference ID already exists in the Dictionary. If it does, replace that reference with the one from the Dictionary.

Alternatively instead of having variables which contain a reference to your YourClass, the variables contain your unique ID. Then every time you want to access the reference you would look up this ID in the Dictionary to get the instance. This is the way that Unity recommends doing this, but requires more refactoring of your code than the first approach.

All the best,
Joel @ Moodkie Interactive
Purchase Easy Save | Contact | Guides | Docs | Getting started

Post Reply