In Reference to this lesson in this course I would like to point out that yes, this is in fact a beginner course where we are trying to understand the basics of coding. But at the same time, we also have to be careful of the performance of our code. We are in fact after all writing games. With that in mind, we want our code to be as fast as possible so that it won’t have an impact on the overall performance of our game.
In the OnCollisionEnter callback function we have the line
GetComponent<MeshRenderer>.material.Color = Color.Red;
Now what this is doing is asking Unity to find us a component, in this case the MeshRenderer and that takes some time for Unity to do, because Unity starts at the top of a game object and works it’s way down until it find what we’re looking for. And if we remember that even a simple Cube has multiple components by default attached to it, So Each time you hit your player up against an object, and the OnTriggerEnter callback is happening, it is searching for the MeshRenderer every single time. and like was previously mentioned this takes some time, it takes some overall game performance to do.
So How can we go about fixing this issue
One common way to fix this issue is called component caching. And what this is, is getting the component beforehand and storing it in a variable so that we can use it later. In this way, we only ever have to call GetComponent<> once.
So how would we go about doing this. Well it is in fact quite simple. We can create a variable to hold a reference or the location of where the MeshRenderer that is associated with our game object. Then in the Start callback function we can use GetComponent<> and assign the result of the search that GetComponent<> can do to our variable. Then finally in OnCollisionEnter() we can make the change to our variable as if we used the original line of code from this lesson, and that would look something like this
public class ObjectHit : MonoBehavior
{
// This is a variable to hold the location of the MeshRenderer Component
MeshRenderer meshRenderer;
void Start()
{
meshRenderer = GetComponent<MeshRenderer>();
}
private void OnCollisionEnter(Collision collision)
{
Debug.Log("You hit the wall");
meshRenderer.material.color = Color.red;
}
}
And this code here will do the same thing that was shown in the lesson, but will save some time because unity isn’t looking through all the components every single time your player hits an object. I know that this is more of an advanced topic to cover at this point. But I do think that it is something worth mentioning and it is also something that you will pick up more along the way as you work more with Unity and you learn about optimizing your code.