Should we be caching GetComponent<Movement>()?

Following along the lecture, I thought that Rick may have cached GetComponent<Movement>() at the beginning of the script, but that didn’t happen.

Shouldn’t we be caching references (am I using “reference” here right?) at the start? I recreated the void Start() method and placed movement = GetComponent<Movement>(); there. Is that the standard place to put all cached references or could I get away with placing movement = GetComponent<Movement>(); within void OnCollisionEnter(Collision other)?

I’m quite new to all of this, so any help/advice would be greatly appreciated :slight_smile:

1 Like

You’re right in that Rick sort of bypassed his own advice and didn’t create a reference to the movement component. For this lesson I implemented my code a bit differently and cached a reference to movement within Start() as a matter of habit, since you are correct in stating that it is standard practice. I think Rick mentioned this in a earlier lesson but since he is only getting the movement component once when the function is called then it is certainly acceptable to “get away” with doing it that way. The only problem would be if you did it that way within Update() which would be calling GetComponent() every frame and could possibly slow down your game. In that case you would def want to create a reference in Start() which is why I think it is standard practice.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms