Does a Singleton allocates memory if they're not being called?

Does a Singleton allocates memory if they’re not being called? For example:

public class CameraShake : MonoBehaviour
{
    // Make it singleton
    #region Singleton
    public static CameraShake instance { get; private set; };
    private void Awake()
    {
        if (instance == null)
            instance = this;
    }
    #endregion
  
    public void Function() {// Code here...}

}

Does it allocate the memory if we DIDN’T call it somewhere?

If you didn’t call what?

The code as presented doesn’t specify a mechanism to create an instance of CameraShake. That being the case, the question of whether something is being allocated isn’t answerable without having more context.

If it were something like a self-instantiating singleton that creates itself whenever the “instance” static property is accessed, then by design, the component won’t be allocated until the property is used.

With the code you wrote here, though, we don’t know when the CameraShake component gets created. That act of creation by AddComponent or being loaded from a serialized scene is where memory (the object) gets allocated.

5 Likes

Well I can only presume he’d attach this component to a gameobject manually. In that case it is allocated immediately on start. But this is true of all components.

3 Likes