x


Why do I have to explicitly DontDestroyOnLoad() my inner variables?

I want my Player object to persist between levels, so I call this in the Start()

DontDestroyOnLoad(gameObject);

And while this worked, this started acting very very strange after the next level loaded. It turns out lots of things the player instance depended on were being destroyed. I ended up with this to make it right.

DontDestroyOnLoad(gameObject);
DontDestroyOnLoad(bullet);
DontDestroyOnLoad(explosion);
DontDestroyOnLoad(renderer.material);

for (var skill : Skill in skillComponents) {
  DontDestroyOnLoad(skill);
}

So I had to mark all my prefab variables to not be destroyed as well as my material.

My question in why? Is there a rule of thumb about what should be marked dont destroy and what should not? The prefabs and objects stored in internal variables I almost get the need, but why on earth would my material need to be explicitly retained?

more ▼

asked Oct 08 '10 at 05:08 AM

Squeegy gravatar image

Squeegy
235 8 10 21

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

From the behavior you describe it seems that your "variables" are actually game objects that are simply assigned to your script. DontDestroyOnLoad(...) has an effect for the game object on which it is called including all the components that are attached to the game object.

However, any other game objects references from that script are not automatically kept. If you need to mark all components of a single game object with DontDestroyOnLoad(...), that would be considered a bug, though.

more ▼

answered Oct 08 '10 at 05:43 AM

jashan gravatar image

jashan
10.1k 25 40 116

Another issue that might be a problem if you call DontDestroyOnLoad on Components instead of GameObjects ... not sure if that's the case for you - but I just ran into an issue with Destroying components instead of GameObjects (which was kind of funny ... it just didn't work as I expected ;-) ).

Oct 08 '10 at 04:39 PM jashan
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x82

asked: Oct 08 '10 at 05:08 AM

Seen: 1557 times

Last Updated: Oct 08 '10 at 05:08 AM