#hello why is Instance returning null

1 messages · Page 1 of 1 (latest)

rustic elm
#

You never set instance

cerulean breach
#

"Instance = this as T;" does not?

#
public class GameManager : MonoBehaviourSingletonPersistent<GameManager>

in execution it works like this

rustic elm
#

ah I see that now :). Though this as T has potential for returning null. Try a hard cast (T) this;

knotty heron
#

this as T is 100% guaranteed to return null

rustic elm
#

actually that's it

#

this is not T

knotty heron
#

since this is a MonoBehaviourSingletonPersistent and not a T, no?

rustic elm
#

it is MonoBehaviourSingletonPersistent<T>

cerulean breach
rustic elm
#

so as Praetor mentions it will 100% return null 🙂

knotty heron
#

if you have MyScript : MonoBehaviourSingletonPersistent<MyScript>

#

that would work

knotty heron
#

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

cerulean breach
#

ohhh okay, interesting how come 'this' does not work?

rustic elm
#

this is the component not the game object

knotty heron
#

because this is the Component, not the GameObject

cerulean breach
#

i wanted to gameobjec to live and the component to die

rustic elm
#

Right, but you're calling DontDestroyOnLoad()

knotty heron
#

really? 🤔

rustic elm
#

that only operates on root level game objects

cerulean breach
#

oh i didn't realisew

knotty heron
#

Yeah DDOL only works on GameObjects

cerulean breach
#

okay thanks guys ill try this stuff out

rustic elm
#

for your instance I would change it to:
public static MonoBehaviourSingletonPersistent<T> Instance { get; private set; }

knotty heron
#

No you definitely want T instance

#

otherwise it's a trashy experience

#

None of this is the problem though

cerulean breach
#

wait does OnEnable run before Awake?

knotty heron
#

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

cerulean breach
#

how do you prioritise which object goes first?

knotty heron
#

The best way is just use Start when accessing other objects

#

and use Awake for self-initialization

cerulean breach
knotty heron
#

no