Skip to main content

Detecting Collisions

The OnCollisionEnter method can be used to detect a collision of a GameObject with another GameObject. In this example we are also using the GetComponent<Renderer>() method to access the object's renderer component, which controls its visual appearance.

We create a new script with the name ChangeColorOnCollision.

Add the following code to the script:

public class ChangeColorOnCollision

 : MonoBehaviour { private Renderer objectRenderer; public Color newColor; void Start() { objectRenderer = GetComponent<Renderer>(); } void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "wall") { objectRenderer.material.color = newColor; } } }