#'The object of type 'x' has been destroyed but you are still trying to access it.', x is Monobehavio

1 messages · Page 1 of 1 (latest)

south shoal
#

This Exception happen 75% of time when i enter playmode, x of mine is monobehavior and got assigned into ecs component F (managed type) from Awake() in one of my monobehavior script (x exists in editor and i just drag and drop it into this script).

  • Class A (is singleton class, not mono), has a method C that is used by OnUpdate() inside a system.
  • Method C simply read data in said component F to get said x, and when the Exception I mentioned at the title occured (Exception shows the line which i use monobehavior method on x), checking x == null return true, I still can use Function that declared in x without any NullRefException,
    But how is this possible?? as I said, x is monobehavior and exists in Editor (and nothing destroy it at runtime), if it is really null, why the Exception occured only when I tried to use Monobehavior methods, not those methods that I declare myself.

Thanks for reading, i will try my best to provide the code cause there are too many files.

tepid jetty
#

it sounds like the instance of x that you are referencing was destroyed due to scene loading

#

or something else destroyed the game object

#

is it in a subscene?

#

is your singleton class properly reset on domain reloads?

south shoal
tepid jetty
#

perhaps try to put a breakpoing in the OnDestroy method of x; it should be called if x == null is true

#

unity objects override the null equality comparison to return true for destroyed objects, but their C# counterpart is not actually destroyed yet (it won't be until it's garbage collected)

south shoal
tepid jetty
#

it works because the C# portion of it still exists, but as soon as you have any call to native code it will complain

south shoal
#

Man, i found the root problem.
It comes from class A (singleton one, i used lazy initialization on it), class A has 2 fields that store 2 managed components (get those components by using constructor).
I don't know why but Unity did not clear class A singleton instance until it recompile, which mean each time i enter playmode, class A instance will use old data from first playmode, that why I got the said Exception

#

this is my class A:

covert elbow
#

See this example:

using UnityEngine;

public class StaticCounterExampleFixed : MonoBehaviour
{
    static int counter = 0;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
    static void Init()
    {
            Debug.Log("Counter reset.");
            counter = 0;   
    }

    // Update is called once per frame
    void Update()
    {
            if (Input.GetButtonDown("Jump"))
            {
                counter++;
                Debug.Log("Counter: " + counter);
            }
    }
}
#

or if you can clear it in a systems OnDestroy