colyseus / colyseus-unity-sdk

⚔ Colyseus Multiplayer SDK for Unity
https://docs.colyseus.io/getting-started/unity-sdk/
MIT License
371 stars 100 forks source link

ColyseusManager destroy game object unexpected or have multiple instance when change scene #214

Closed lcd11001 closed 1 year ago

lcd11001 commented 1 year ago

ColyseusManager

In Unity's MonoBehaviour Persistence pattern, where you want to have a single instance of a MonoBehaviour across multiple scenes, using Instance = this as T instead of Instance = GetComponent() serves a specific purpose.

Here's why Instance = this as T is used:

  1. Preserving the Instance: When you move between scenes in Unity, the GameObjects and their attached components, including MonoBehaviours, get destroyed and recreated. If you use GetComponent() in the Awake() or Start() method to find the instance, it will only find the instance on the same GameObject. In other words, it will only find the instance if it exists on the newly created GameObject, which is not the desired behavior for a persistent singleton.

  2. Singleton Initialization: By using Instance = this as T, you ensure that the first instance of the MonoBehaviour will be assigned to the Instance variable. The as keyword performs a cast, trying to cast this to the generic type T. If the cast is successful, Instance will be assigned the reference to this, which is the first instance of the MonoBehaviour.

It's important to note that subsequent instances of the MonoBehaviour will not pass the this as T check, so they won't overwrite the Instance variable. This guarantees that only the first instance of the MonoBehaviour will be assigned as the persistent singleton.

To summarize, using Instance = this as T ensures that the persistent singleton instance is properly assigned, regardless of the scene changes, while GetComponent() would only find the instance on the same GameObject, potentially leading to multiple instances in different scenes.

endel commented 1 year ago

Hi @lcd11001, thank you for the detailed explanation, this sounds great! Would you like to create a pull request for this? I could apply your fix myself but it would be nice to have your name listed as a contributor here with your pull-request if you'd like to. Cheers!

lcd11001 commented 1 year ago

No, thank you @endel ! Just a small contribute. I would like to get update version to 0.15.3 ASAP for my Unity project.

endel commented 1 year ago

Thank you @lcd11001, released at 0.15.3