Can you cache Camera.main and/or other gamecomponents in a lambda expression?

Like this:

private PlayerInput _playerInput => GetComponent();
private Camera _mainCamera => Camera.main;

Will using the those variables just constantly do use the GetComponent function and stuff, or is the reference cached when the code is compiled and the variable already has the reference ready?

Pretty sure using lambda expressions this way isn’t really any different from declaring it inside a method, so it will run GetComponent every time.

  1. Welcome to the Unity forum :slight_smile:

  2. You might want to profile if Camera.main actually is a bottleneck for you. It got way faster (like 20.000 times faster) with Unity 2020: Unity Blog

  3. For future questions, please use code tags when posting code snippets The likelyhood of getting replies also increases by about 20.000% if you use them :wink:

  4. Understanding the concept of “closures” might help you to reason about your question:
    c# - Deep diving into the implementation of closures - Stack Overflow

Can you? Yes. Does your code do that? No.

A cached reference in a property would look something like:

private Camera mainCamera {
get {
if (_mainCamera == null) _mainCamera = Camera.main;
return _mainCamera;
}
}
private Camera _mainCamera;
2 Likes

We recently had a similar thread here and I posted this solution .