• Twitter
  • Facebook
  • Google+
  • Instagram
  • Youtube

Tuesday, 20 September 2016

PlayerPref or DontDestroyOnLoad?

I was making a game that requires to pass some data between scenes.
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"
I agree. However, using PlayerPrefs doesn't follow the rule of optimization.

0 comments:

Post a Comment

Contact

Get in touch with me


Adress/Street

Jozi Studio -Sydney, New South Wales

Phone number

+(12) 3456 789

Website

www.learnwithjoe.blogpost.com.au