- Home /
Chest contents persistence between scenes
How do I keep chest contents persistent between changing scenes or loading game?
Lets say for example that in Scene1 I have chest with three items in it. Player interacts with chest and take out only second item. Then player moves to Scene2 and later returns to Scene1. After loading chest will return its content to default, so all three items will be there again. Same thing will happen when player close and load game again.
How do I make chest "remember" what was taken out? I guess I can record every chest GameObject or Script (...or only List<> of items inside of it) in save file but maybe there is some better method?
How do I handle this properly?
No matter what you do, you will have to store somewhere the chest contents. You can do it by storing it in the level data, or in a level database. This also means that your chest contents need to be loaded from somewhere the first time as well (or generated, but that's almost the same thing).
You could put a script onto any gameobject and add the [DontDestroyOnLoad] attribute. Have this script keep track of your chest contents, for example by having one variable for each chest (or in a collection of some sort). When loading a scene, you just find the chest and assign the contents based on your script (which is kept between scene changes).
Alternatively, as Harinezumi, save and load the data along with your level data via BinaryFormatter etc.
you can use PlayerPrefs to save your stats ,if you go to another scene or even leave the game, your stats won't change this will save your stats in registry.
for example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public int test;
public void Start(){
test = PlayerPrefs.GetInt ("test");
test += 10;
PlayerPrefs.SetInt ("test",test);
}
so at the first time you play this script, it will return 10,second time 20, and ....
It's just an example to give you the idea.you can check if the player picked up items and if it was true the item should not be spawned in the chest :).
It's generally not considered good practice to use PlayerPrefs to save game data (it's intended for options, configuration, preferences, etc). This official unity tutorial has a section showing how to use BinaryFormatter to save game data.
Very true! PlayerPrefs are - as the name suggests - for configuration data, if you want to store anything more complicated then saving on disk is a better solution (although on mobile devices this becomes more tedious than with PlayerPrefs).
Your answer
Follow this Question
Related Questions
Loading error when using PlayerPrefs.GetInt with WebPlayer 2 Answers
can gameobjects be stored as static? 1 Answer
Saving lots of objects 1 Answer
Complicated save problem 2 Answers