Storing a reference to a non-UnityEngine.Object

Examples using Easy Save's API code
Post Reply
User avatar
Joel
Moodkie Staff
Posts: 3782
Joined: Wed Nov 07, 2012 10:32 pm

Storing a reference to a non-UnityEngine.Object

Post by Joel »

Sometimes it is necessary to store a reference to a non-UnityEngine.Object.

As Unity doesn't support references of these types, you will need to make a manager of your own to create unique IDs which you can store instead of the object itself.

This fully-commented example demonstrates how you might do this. It is likely that some alterations will need to be made for it to work for your specific project, but this should be detailed enough to show you the general principles.

To use this example, import Easy Save into a new project before importing this UnityPackage. Then open the ClassReferenceExample scene in the ClassReferenceExample folder. The first time you play the scene, it will assign a MyClass object to every MyScript object. Then when you close and reopen the scene, it will instead load the MyClass object from the file.

In this example we have the following scripts:
  • MyGameManager creates a MyClass object and assigns it to all of the myClass variable of all MyScript objects in the scene. It also manages saving and loading of MyScript and MyClass objects.
  • MyScript is a MonoBehaviour which references a MyClass object.
  • MyClass is a class which does not inherit from UnityEngine.Object. It also contains a static Dictionary which contains every MyClass object and it's unique ID.
When the game loads, it checks if there is any save data. If there isn't, it creates a new MyClass object and assigns it to all of the MyScript objects in the scene. Otherwise, it loads the Dictionary of MyClass objects before loading the MyScript objects.

When the Application quits, the Dictionary of MyClass objects is saved, followed by the MyScript objects.

For more detail, please read the comments in each of the scripts.
Attachments
ClassReferenceExample.unitypackage
(4.91 KiB) Downloaded 38 times
Joel @ Moodkie Interactive
Purchase Easy Save | Contact | Guides | Docs | Getting started

Post Reply