Unity Change 3D Object Color On Collision | Unity Tutorial
In this Unity tutorial, we’ll explore how to change the color of a 3D object when it collides with another object. This step-by-step guide will show you how to set up a scene with 3D objects, configure colliders and Rigidbody components to detect collisions, and write a C# script to handle color changes during those collisions. Additionally, you’ll learn how to use Unity’s tag system to specify which objects should trigger the color change. By the end of this video, you’ll have a practical understanding of how to dynamically alter object colors in response to collisions, enhancing the interactivity and visual appeal of your game. Ideal for beginners and anyone looking to refine their Unity skills!
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
Unity Projects - ON SALE!!!
1. Water Sort Puzzle 9000 Levels
2. Ball Sort Puzzle 9000 Levels
3. Sling Shot
=========================================================
Scripts:
ColorChangeOnCollision.cs
using UnityEngine;
public class ColorChangeOnCollision : MonoBehaviour
{
[SerializeField] private Color collisionColor = Color.red; // Ensure this is visible in the Inspector
public string targetTag = "Collider"; // The tag of the object to check for collision
private Renderer renderer;
private Color originalColor;
private void Start()
{
renderer = GetComponent<Renderer>();
if (renderer != null)
{
// Clone the material to ensure changes only affect this object
renderer.material = new Material(renderer.material);
originalColor = renderer.material.color;
Debug.Log("Original Color: " + originalColor);
}
else
{
Debug.LogError("Renderer component not found on the GameObject.");
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag(targetTag))
{
if (renderer != null)
{
renderer.material.color = collisionColor;
Debug.Log("Color changed to: " + collisionColor);
}
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag(targetTag))
{
if (renderer != null)
{
renderer.material.color = originalColor;
Debug.Log("Color reverted to original.");
}
}
}
}