as Mentioned in title a weird effect of going to next scene by static variable singleton
I always use singleton and its always working correctly but not this time .
I’m not using dontDestroyOnLoad of course cuz its a static var
I can work around the issue by using dontDestroy but am here to learn sth new about singeltons
any body could help? Thanks
TheCode
public static DashBoard_Ref DbR_Instance;
void Start()
{DbR_Instance = this; }
forget to say its working in calling its methods (no nullref excep)
but the problem showed up to me when I intended to use {If check} → if(DashBoard_Ref.DbR_Instance != null)
its false means its null but with no nullexception -when using methods without if- as mentioned …
Have you tried making it a static class instead ? I don’t see the full script, but I suppose it is running in a Monobehaviour.
I’m not using dontDestroyOnLoad of course cuz its a static var
The both are not related. For a Singleton instance of a monobehavior class, the instance acts as a “link” to a component, which is attached to a gameObject.
Should this object be deleted (changing a scene for example), then your singleton instance returns null. If you do not need the monobehavior components then do a static class
public static class DbR
{
// your functions and variables
}
and access it with “Dbr.myVariable” or “Dbr.myFunction()” . This way, it will act as a singleton, and won’t be impacted by scenes changes, because it won’t be attached to a GameObject (because it is not a monobehavior).
If you need it to be a monobehavior, then either use DontDestroyOnLoad or load your next scene additilvely (more complexe).
This problem is caused by the order in which the scripts are executed. If you call DashBoard_Ref.DbR_Instance before DashBoard_Ref’s Start() function is called, it will be null. To fix this problem, you can assign static variable in Awake() function, and use it only in Start() function. You can also edit the order in which the scripts are executed (not recommended). Order of execution for event functions