I have a player with its references to its own components like collider/rb in a player.cs script. The thing is, referecing manually in the engine makes it look ugly, and I was wondering :
Is referencing like
rb = this.GetComponent<Rigidbody2D>(); is okay ?
It may use a lot of ressources as a level of my game is composed of multiple scenes and there’s no DoNotDestroyOnLoad object, so it searches anew in each scene.
It helps to keep cleaness in my inspector ^^', tough I can help a little with Headers.
That’s is actually the standard approach for objects not initialized in the inspector (dynamically, or in code-focused projects), but a key consideration is caching. If you’re calling GetComponent every frame, that may lead to performance bottlenecks, especially dangerous as the number of attached components increases. You will be fine with caching the references and then just calling them as you need them.
See an example of how I set up my MonoBehaviors with Rigidbodies below. You can of course do this with any components.
public class PlayerMove : MonoBehaviour
private Rigidbody _rg;
private void Awake()
_rg = GetComponent<Rigidbody>();
private void FixedUpdate()