- Home /
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.
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 :)
Answer by unity_ka6jgzfPPmtNCw · Nov 15, 2021 at 10:26 AM
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.
Your answer
Follow this Question
Related Questions
Arrays/Lists in the inspector of Editor Extension scripts 0 Answers
There is no GameObject attached to this GameObject 2 Answers
Assign video in inspector via script 0 Answers
Reorderable list of UnityEvents 2 Answers
Effects architecture akin to Starcraft 2 0 Answers