Retaining GameObject data when switching scenes?

I'm making an RPG, and wanted to know how I would be able to retain a GameObject's possibly changed data/variables (such as HP, coordinates, etc.) when switching scenes. I am asking this because when a new scene is loaded all of the previous scene's GameObject's (such as the character object in that scene) data/variables (HP, etc.) will be set to their defaults and all of that mandatory info would be lost.

Any help would be appreciated. Thank you!

You could call Object.DontDestroyOnLoad(myGameObject); and then just keep the same gameObject from scene to scene.

You could do PlayerPrefs.SetInt(“string”, int);
This basically allows you to store integers on the computer, and it would save this even after the game is closed. For example:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
	public int gold;
	public int health;

	public void loadLevel () {
                 PlayerPrefs.SetInt("HP", health);
                 Playerprefs.SetInt("Money", gold);
	}
}

Then in the next level make it go:


using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
	public int gold;
	public int health;
	// Use this for initialization
	void Awake () {
                 health = PlayerPrefs.getInt("HP");
                 gold = PlayerPrefs.getInt("Money");
	}
}

There’s a lot more information in the documentation (just do Ctrl+" on PlayerPrefs in MonoDevelop).

You could also consider creating a "checkpoint" before level changes where all Data are written e.g. in a Savegame/File/Database and reloaded (respectively only the data needed for the new level) after every level change. Thus you can purge the memory from data unneeded for the scene (e.g in a indoor scene you barely need cooridates of visited places or other data related to outdoor levels)

Another approach (not the best but an easy one) would be making static objects which can store player data. Those objects don't need an instance to be altered, but be careful to reinitialize those objects appropiately.

With static objects, you can also avoid passing lots of data from one object to another, or keep looking for objects every scene like in DontDestroyOnLoad() or store data Methods, but player data will be always on memory, and most programmers consider using static objects a bad programming habit.