Search code examples
c#unity-game-enginemobilestartup

Cache property (get) vs lazy initialization to safely GetComponent before awake in unity (mobile platforms)


  • I need to cache a great number of components at startup (and I cannot reference them in the monobehaviour directly)
  • I can't be sure when they will be requested (so I cannot cache them in Awake, because they could be requested from an Awake of another Monobehaviour)

My starting solution was to use a public get property, that was the pattern I'm more familiar with. But now I'm trying Lazy initialization (that is more readable).

Getting Components As Property

    // --------------- COMPONENT AS PROPERTY --------------- //
    private ComponentRequired _componentAsProperty;
    private ComponentRequired _ComponentAsProperty
    {
        get
        {
            if (_componentAsProperty == null) 
                _componentAsProperty = GetComponentInChildren<ComponentRequired>(true);
            return _componentAsProperty;
        }
    }

Retrieving Component As Lazy

    // --------------- COMPONENT AS LAZY --------------- //
    private Lazy<ComponentRequired> _componentAsLazy 
                => new Lazy<ComponentRequired>(GetComponentInChildren<ComponentRequired>(true));

I also read Cached property vs Lazy<T> (that was related to instantiation) and the same answer might apply to lazy retriaval of components.

Performance wise I did not find a great difference at the moment on the profiler, but I want to ask to make sure of any possible drawbacks with unity and components (especially for mobile platforms).


Solution

  • For Unity it is better to avoid the Lazy implementation, because it can move out of the main thread (and GetComponent cannot be used outside of the main thread).

    At this version of unity 2019.1.7, it's much safer to use properties to cache any component.