About the Singleton bug

What exactly is the bug ? Why the bug happens ? Can you please elaborate it ? I’ve seen the video. But that doesn’t seems to answer the two questions. Rick only gives the solution.

Hi Allan,

The problem is the following: The Destroy method destroys the object with a delay. This delay is sufficient for FindObjectOfType to find the active object which is about to get destroyed.

However, FindObjectOfType of type can find active objects only. By disabling the object, it cannot find it anymore. Disabling works immediately.

Did this clear it up for you?

We are finding the objects just to know the no of objects present and it is only assigned in a variable. How it causes the Bug? I dont really get it?

When we load a new level, and there is another object of the same type in that scene, it might be that FindObjectOfType finds that other object. Then the “singleton” destroys the superfluous object, and we get a NullReferenceException.

FindObjectOfType returns the “first” active object it finds, whatever Unity defines as “first”.

Yes. we destroy the new object while pertaining the existing object. But what’s exactly the error? . I still don’t get it. sry.

The problem is that Unity has got enough time to find the “wrong” object because the “wrong” object still exist for a brief moment. Then that object gets destroyed, but your code still tries to access that object.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms