Now, because inside hit we store the info of what we “hit”,
in the Debug.Log() we can easy try to grab the name of the object we hit.
If we change the code like this
If we test it now
We see the name “Cube” in the Console.
And now, we can simply grab the
Component<MeshRenderer>().material.color and change it
I use Random.ColorHSV() to generate a Random Color
Now we are raedy to test it
And everything is working really good.
This is just a test, but to make the things better, we need a null check because, we know, is best practice and is better we don’t forget to do it.
So, we change some line of code
we take a reference to the MeshRenderer, and we check
if != null, change the color.
This is work really well, and if we duplicate the Cube or we create a Sphere (and attached the script), it works without any problems.
Now, if we want change color ONLY to the Cube?
For example, if we have Cube, Sphere and Cylinder.
The easy way is use Tags, and again, we have every information inside “hit”
So we create a tag (for semplicity I used the tag “Player” for the Cube)
We simply access to the collider.transform.gameObject.CompareTag(“Player”)
thanks to “hit” variable
and this is the result.
Obviously, if we want different behaviours for every object, we need all the right “tags” and maybe a Switch Statement to see every cases.