Is it ok to use nested classes, to cache and access components?

Hi Community!

I am using a nested class to cache referenced objects and components in my scripts:
_
public class PlayerBehaviour : MonoBehaviour
{
[System.Serializable]
private class References
{
public GameObject bullet;
public GameObject spawnpoint;

        [System.NonSerializable] public Transform transform;
        [System.NonSerializable] public Rigidbody rigidbody;
        [System.NonSerializable] public Renderer renderer;
    }

    [SerializeField] References cached;

    private void Start()
    {
        cached.transform = GetComponent<Transform>();
        cached.rigidbody = GetComponent<Rigidbody>();
        cached.renderer = GetComponent<Renderer>();
    }
}

_

I do this, because I think it has some great advantages. For example, I don´t have to come up with creative variable names, like rgbd, myTransform or similar, and just can use cached.transform and cached.rigidbody, without getting in conflict with engine-used members.

Also I can collapse and separate public references from other public variables in the Inspector, which, I think, looks a lot cleaner as if there is all mixed together on one level.
_
188723-inspector.png
_

Unfortunately, I don´t have the deepest knowledge in C# architecture and internal Unity tasks. The Profiler and overall performance of my projects doesn´t seem to have problems with that, but I havn´t rolled it out on many scripts at the moment.

My Question is, do you know if there are any major downsides of this solution?
_
Thank you in advance :slight_smile:
_

You can do it. There’s no problem.

It can add a level of unnecessary abstraction but if you think it serves a purpose you can do it.