Cached Referencing

Hi, so far I’m really enjoying the course it’s really concise and the teaching method is very good. I would love to leave a 5-star review at the end of the course.
I am a little bit confused I will try to write the code below for clarification.

private Level level;

I know this is to let the compiler know that this variable is a type of Level aka The script I named Level

level = FindObjectTypeOf<Level>();

Now here it confuses me. I have already initialized the level variable as Level then why do I have to tell it again in the FindObjectTypeOf<>();?

Hi @Ishtiaq01,

Thank you for your question.

That’s correct. We declare a variable here and let the compiler know that the variable is of type Level.

By default, the value of variables like these is null, which means “no reference to an object”. Reference is something like a link. If we did not assign an object to level, we would get a NullReferenceException error if we tried to access an object via level during runtime. Maybe you’ve already encountered that error. It’s fairly common.

FindObjectTypeOf() returns an object of type Level if there is one in the scene. If there is none, it’ll return null. We assign the returned value to level.

Did this clear it up for you? :slight_smile:


See also:

1 Like

Thank you so much @Nina for your response. I really appreciate the time and efforts in explaining it.

1 Like

You’re welcome. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms