After googling, I came up with a solution which is using DontDestroyOnLoad.
The code is simple as it is. In Start/Awake function, add this code:
DontDestroyOnLoad(gameObject);
- it will "re-create" when loading other scenes.
- the object could store everything as component's data.
- easy to use
Problem: it cause leak when moving between scenes
Example: Scene A has object X that turned to DontDestroyOnLoad
From scene A, load Scene B --> Scene B has object X (in DontDestroyOnLoad)
From scene B, load scene A --> scene A now has two objects of X (in DontDestroyOnLoad)
Solution: The solution provided by Nate River solved.
After add object into DontDestroyOnLoad, add this code
if (FindObjectsOfType(GetType()).Length > 1)
{
// delete the object if it already exist
Destroy(gameObject);
}
From Stepan's explanation, he will not use DontDestroyOnLoad at any cost. He suggests to use PlayerPrefs because of his reasons:
- PlayerPrefs is a persistent storage of data.
- "a fairly traditional and easy to use place to put your savegames"
0 comments:
Post a Comment