Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Confusing Behavior with DontDestroyOnLoad

Discussion in 'Scripting' started by rsoliloquy, Mar 11, 2016.

  1. rsoliloquy

    rsoliloquy

    Joined:
    Nov 13, 2015
    Posts:
    13
    I'm a bit confused by this behavior I've bumped into and I was wondering if anyone could explain why it occurs, and perhaps potential work-arounds as it's gotten quite in my way.

    I have a public list of a class HeldItem. All HeldItems it contains are unique and not references to existing items in the scene. However when I change scene (and the object with this list has DontDestroyOnLoad set), this list's content becomes garbage. This didn't make sense to me since the content isn't a part of the scene and thus shouldn't be destroyed by a scene change. At least, that's how I reason it. I don't actually know much about how Unity handles changing scene. Eventually I discovered that making the entire list private will for some reason prevent this destruction of the data. However, that in turn requires me changing a ton of random code to account for that.

    Why is this data being removed? Is there any other way to stop this data's removal than making the entire list private? Thanks.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    define "garbage"...

    If preventing other things from accessing the list (public => private) stops the list from being changed into "garbage" I would posit the issue is in the "random code" which is accessing/updating the list rather than the list itself.
     
  3. rsoliloquy

    rsoliloquy

    Joined:
    Nov 13, 2015
    Posts:
    13
    I'm not totally sure, attempting to access any of the items in the list just results in an error. So I'd assume, the memory associated with the list has been let go, resulting it in it accessing random memory when trying to access an item. The problem is certainly not in what's accessing it, as I can do something so simple as set it up to print out of the name of the first item in the list each frame and it will do so fine until switching scenes, at which point the print call will begin resulting in an error. The problem is definitely in the list itself.