Why implementation of Singleton Pattern at scorekeeper doesn't cause error?

So, I understand singleton pattern as Guarantee specific object exist one and only.(Plus, it make other object easy to access.)

But Isn’t it make potential problem if we manage singleton and get reference of scorekeeper at the same time-at Awake() method-? Cause if we load another scorekeeper at new scene and get reference at awake(), there is possibility that we get wrong scorekeeper first and destroy it later.

For this case, If we load game scene after game over menu, another scorekeeper is loaded from scene file, and it needs to be destroyed before UiDisplay accidentally get reference of new one. Otherwise, after UiDisplay get reference of new one, It will be destroyed so that UiDisplay have NULL reference.

But after I play test several times, I can’t find any error. UiDisplay always display score right. Why it works without potential problem.?

Why were you expecting it not to work?

I have the same question.

In the Singleton class, extra instance is destroyed on Awake(). And other classes access the singleton instance by calling Findobjectoftype() also on Awake(). IIUC, the execution order of Awake() between classes could be random. Then Findobjectoftype() might be called before the destroy of extra instance and hence return the wrong instance?

A possible answer I can think of is that Findobjectoftype() always return the oldest instance(can’t find it on official documentation though, just my guess). And the oldest instance is always the right one in this singleton use case.

I think you are 100% correct with that assumption. The documentation says the following:

Returns the first active loaded object of Type type .

The first active object will always be the object that wasn’t destroyed when loading a new scene, so it will always work according to that sentence.

The definition of “first” in the documentation is not clear to me though. The first one returned by Findobjectoftype() could be the wrong instance that will be destroyed later depends on how Unity sort objects of the same type. In my previous comment, I was assuming “first” = “oldest”, i.e. Unity sorts the object by its creation time.

After testing this 10,000 times, I didn’t encountered any sort of issue, so you can rest assured that this method works fine for this purpose.

If you are truly worried about racing you could use the observer pattern combined with the singleton pattern, use lazy values or even use FindObjectsOfType and search for the correct one with any sort of condition, but to be fair, not encountering an error after 10,000 tests pretty much says that the method is 100% safe.

Privacy & Terms