#How to subscribe to singleton events in a correct way

1 messages · Page 1 of 1 (latest)

edgy ruin
#

Ive been told to use OnEnable and OnDisable but subscribing in OnEnable leads to NullReferenceException, since singleton instance value is not assigned yet. I dont want a quick workaround.

wild frigate
#

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;
    }
}
sterile dagger
#

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

celest frost
#

You don't need to the singleton in that case. You can subscribe to NetworkManager.OnConnectionEvent directly

devout zodiac
#

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

edgy ruin
#

Woow thank you for so many answers

edgy ruin
edgy ruin
#

oh sorry for ping

edgy ruin
#

simonp your text is the hardest im still trying to comprehend

celest frost
#

You have to wait for the Singleton to be initialized first. Start() should work fine for you

devout zodiac
#

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)

edgy ruin
edgy ruin
devout zodiac
#

no, that relies on them being in the same scene

edgy ruin
#

well, i guess Start() is the way then

#

thanks

devout zodiac
#

it's the quick fix for sure

edgy ruin
#

grrr