Safe Data between scenes

Hello

So if got a scene with some stuff. Now I wan’t to safe some data if I swicht to another scene.

Concretly that would be a Inventory witch I have no clue how to describe so I’ll post the code down below and two intigers for the lifecount and the money, these are all stored in the same script. Additionally I’d like to safe everything that was done in the scene e.g. which enemys were killed and which items were collected so it looks the same way when I return to the scene.
Plus what was bought in the shop, that workes basically the same way as the Inventory of the player but is stored in another script.

I did look in to several tutorials so I know there are multiple ways to do this but I have no clue what is the best option for me. I’m not sure whether what I explained gives you a good view of what I need but if you have a idea I’d be flattered to hear your input.
I’d also like to store this data when I close and reopen the game or to be able to store multiple game progresses at the same time and load them individually from the menu, but that is for the future so it would be nice if your strategy allows for this but it’s not necessary.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

The inventory code:
public class Inventory
{
    public List<Item> itemList = new List<Item>();
    public int inventorySize = 21;


    public Inventory()
    {

    }

    public void AddItem(Item item)
    {
        itemList.Add(item);
    }

    public void RemoveItem(int itemIndex)
    {
        itemList.RemoveAt(itemIndex);
    }
}

In my main code:

private void Awake()
    {
        inventory = new Inventory();
    }

Thanks for your time

We don’t either, since we don’t know you or your game.

You should instead pick one method and move forward.

You will learn stuff and you will learn what does and does not meet your needs.

This is how engineering works. You refine your approach based on how it goes.

Here is some more reading:

Load/Save steps:

https://discussions.unity.com/t/799896/4

An excellent discussion of loading/saving in Unity3D by Xarbrough:

https://discussions.unity.com/t/870022/6

Loading/Saving ScriptableObjects by a proxy identifier such as name:

https://discussions.unity.com/t/892140/8

When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. The reason is they are hybrid C# and native engine objects, and when the JSON package calls new to make one, it cannot make the native engine portion of the object.

Instead you must first create the MonoBehaviour using AddComponent() on a GameObject instance, or use ScriptableObject.CreateInstance() to make your SO, then use the appropriate JSON “populate object” call to fill in its public fields.

If you want to use PlayerPrefs to save your game, it’s always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:

https://gist.github.com/kurtdekker/7db0500da01c3eb2a7ac8040198ce7f6

Do not use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.

https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide

Keep in mind that inventories are HARD.

These things (character customization, inventories, shop systems) are fairly tricky hairy beasts, definitely deep in advanced coding territory. They contain elements of:

  • a database of items that you may possibly possess / equip
  • a database of the items that you actually possess / equip currently
  • perhaps another database of your “storage” area at home base?
  • persistence of this information to storage between game runs
  • presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
  • interaction with items in the inventory or on the character or in the home base storage area
  • interaction with the world to get items in and out
  • dependence on asset definition (images, etc.) for presentation

Just the design choices of an inventory system can have a lot of complicating confounding issues, such as:

  • can you have multiple items? Is there a limit?
  • if there is an item limit, what is it? Total count? Weight? Size? Something else?
  • are those items shown individually or do they stack?
  • are coins / gems stacked but other stuff isn’t stacked?
  • do items have detailed data shown (durability, rarity, damage, etc.)?
  • can users combine items to make new items? How? Limits? Results? Messages of success/failure?
  • can users substantially modify items with other things like spells, gems, sockets, etc.?
  • does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
  • etc.

Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

Or… do like I like to do: just jump in and make it up as you go. It is SOFT-ware after all… evolve it as you go! :slight_smile:

Breaking down a large problem such as inventory:

https://discussions.unity.com/t/826141/4

2 Likes

Do I see that right that there is no shortcut to saving the positions and activness of gameobjects?
My idea which I’m going to try now is to keep track of the state of every gameobject in my scene with a separate script in a list or smthing and than save this list. Is that a good approach?

it’s not a bad approach if that’s what you’re asking.
depends a lot on your game and the ways you’ll be using this.

I used playerprefs a couple of times for mobile games and it was a breeze to work with, but this was Unity 4.x and my save state was idk 12 variables. nowadays with my latest project I intend to flesh out a full savegame system for the desktop PC, and I will probably use a combination of binary and json. in this game I will have a lot of accumulated inventory, and this can only grow in time, per session, and so I have to plan along not only how my savegame is supposed to work, but how I’m managing this in memory as well, because this will affect my approach to serialization as well as the performance.

the other important piece is that my project is almost entirely procedural, so there is almost no static data to be loaded except for the granular content. but your mileage may vary. each project is likely very different from the next one, and so there is a lot to research.

you got a nice compilation by Kurt up there.

If you want a general load / save system, AFAIK the work has to be done somewhere.

If you just need to save a bunch of stuff, as long as you don’t run out of memory, one approach is to parent all the stuff you’re saving under a new empty GameObject, then turn it off with SetActive(false);

Then use additive scene loading and unloading to load up your inventory and dismiss it.

I use separate scenes for all my popups: bring them up by additively loading a scene, have them overlay the main gameplay, which I freeze, then dismiss the popups by unloading their scene.

Additive scene loading:

https://discussions.unity.com/t/820920/2
https://discussions.unity.com/t/820920/4

https://discussions.unity.com/t/824447/2

A multi-scene loader thingy:

https://pastebin.com/Vecczt5Q

My typical Scene Loader:

https://gist.github.com/kurtdekker/862da3bc22ee13aff61a7606ece6fdd3

Other notes on additive scene loading:

https://discussions.unity.com/t/805654/2

Timing of scene loading:

https://discussions.unity.com/t/813922/2

Also, if something exists only in one scene, DO NOT MAKE A PREFAB out of it. It’s a waste of time and needlessly splits your work between two files, the prefab and the scene, leading to many possible errors and edge cases.

Two similar examples of checking if everything is ready to go:

https://discussions.unity.com/t/840487/10

https://discussions.unity.com/t/851480/4

1 Like