#hello why is Instance returning null
1 messages · Page 1 of 1 (latest)
"Instance = this as T;" does not?
public class GameManager : MonoBehaviourSingletonPersistent<GameManager>
in execution it works like this
ah I see that now :). Though this as T has potential for returning null. Try a hard cast (T) this;
this as T is 100% guaranteed to return null
since this is a MonoBehaviourSingletonPersistent and not a T, no?
it is MonoBehaviourSingletonPersistent<T>
hm, out of interest how?
so as Praetor mentions it will 100% return null 🙂
Well it actually depends on the context
if you have MyScript : MonoBehaviourSingletonPersistent<MyScript>
that would work
i do
the other possibilities are that you don't have this object in your scene at all - OR you are trying to read Instance before it is populated
btw DontDestroyOnLoad(this); won't work right
it needs to be DontDestroyOnLoad(gameObject);
same with Destroy(this)
unless you are purposely leaving the GameObject alive
ohhh okay, interesting how come 'this' does not work?
this is the component not the game object
because this is the Component, not the GameObject
i wanted to gameobjec to live and the component to die
Right, but you're calling DontDestroyOnLoad()
really? 🤔
that only operates on root level game objects
oh i didn't realisew
Yeah DDOL only works on GameObjects
okay thanks guys ill try this stuff out
for your instance I would change it to:
public static MonoBehaviourSingletonPersistent<T> Instance { get; private set; }
No you definitely want T instance
otherwise it's a trashy experience
None of this is the problem though
One of these is your actual problem:
#1089973009139372172 message
wait does OnEnable run before Awake?
It goes this way:
Object A Awake
Object A OnEnablke
Object B Awake
Object B OnEnable
and so on
If you want to use Instance it should only be done from Start or later
how do you prioritise which object goes first?
The best way is just use Start when accessing other objects
and use Awake for self-initialization
so like
Obj A Awake
... OnEnable
... Start
right?
no