Explanation on cached reference

Hey,
Can someone explain in more details exactly what’s the meaning of cache reference?
Why couldn’t we just write under Start() SceneLoader sceneloader; (instantiating) to use the SceneLoader class methods.?
Why do we need the FindObjectOfType() method under Start() to use the class’s methods?

Can you show a code example. At first glance, I would say, that scope comes to mind. If you call SceneLoader sceneLoader; in start the sceneLoader would only be visible in that function call and could not be used outside. So if we have a global variable SceneLoader SceneLoader; then during start we find and set the object you can use it elsewhere.

Not sure if that makes sense or I am understanding the question.

So basically in C# declaring a variable inside a function makes the variable a local variable.?
And why do we need to find the object ( FindObjectOfType() )? Is this a rule of C# or Unity?
Thanks

Hi Niv,

That’s right. The “local” refers to the scope of a smaller code block within your class, for example, a method code block. Other methods cannot see the variable which you declared in a method.

Unity. Neither your computer nor C# nor Unity know what you want them to do. You’ll have to explicitely tell them what is supposed to happen, for example: “Get me an object of type Player.”

Have your questions been answered? :slight_smile:


See also:

Thanks
But why can’t we just use SceneLoader.SomeMethod() for example - because I remember we did it in one of the previous lectures?
Can’t we just refer the SceneLoader class and then the wanted method.?

1 Like

If SomeMethod() is static, you can call it via SceneLoader.SomeMethod().

1 Like

Hey, so I think what you might be thinking of is the SceneManager class. Rick had us call that to load the “Game Over” scene for the Lose Collider. The reason why we’re using the FindObjectOfType method is because we want it to find the SceneLoader script so that we can use it to call upon a specific method that we created (LoadNextScene() ).

I imagine if you had the Level script access the SceneManagement namespace then you could use the SceneManager class to specifically load your next level by name. But by using it the way Rick showed us, it will use our method to just load up the next scene as determined by the build settings.

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

Privacy & Terms