#How to subscribe to singleton events in a correct way
1 messages · Page 1 of 1 (latest)
The problem is not the subscribing, but that the instance isn't assigned. You can use a property that initializes itself so it's guaranteed to be always assigned when accessed:
private static NetworkManager instance;
public static NetworkManager Singleton
{
get
{
if (instance == null)
{
// assign value here
instance = ...
}
return instance;
}
}
If you can create the singleton where-ever you can do as Nitku told you, if your singleton is created in a dedicated factory you need to check at what point this runs and maybe move the creation up so you don't run into this race condition
You don't need to the singleton in that case. You can subscribe to NetworkManager.OnConnectionEvent directly
this code is using NGO so modifying how the NetworkManager singleton works is probably unrealistic
NetworkManager.Singleton is assigned in the network manager component's own OnEnable method so if you want to do it that way, you have to make sure somehow that your own code is running after that point
if this is for an object that's in the same scene as your NetworkManager when you start the game, you could skip Singleton and just add a a serialized reference directly to the NetworkManager
Woow thank you for so many answers
The problem with that its that its not my Singleton, rather a built in class in the NGO, which doesnt have this code.
Im not speaking of this particular case only but thanks anyways
oh sorry for ping
I dont understand, are you and nitku suggesting me to create a new instance of class inside of code? But its a monobehaviour and im storing it on a gameobject in the scene
simonp your text is the hardest im still trying to comprehend
You have to wait for the Singleton to be initialized first. Start() should work fine for you
the very general answer is "don't write code that relies on the order of unity events", either by controlling the order of events yourself (have a setup script which activate or spawns the network manager then your own script), or by designing it so the order doesn't matter (using a serialized reference or something like that so it doesn't matter if the network manager hasn't been enabled yet)
Is it logical, then, to unsubscribe in OnDisable(), since it wont subscribe back in OnEnable()? Or should i subscribe in both OnEnable() and Start() then?
sounds reasonable. would it find the DontDestroyOnLoad object on scene reload tho?
no, that relies on them being in the same scene
it's the quick fix for sure
grrr