Bring some color to your scene with this easy-to-implement technique for changing object color on mouse click!

Unity Quick Tips: Changing Object Color on Mouse Click

Part 7 of Our Bite-Sized Unity Tips and Tricks for Beginners

Valdarix Games
3 min readFeb 19, 2023

--

Welcome to Part 7 of our series of bite-sized Unity tips and tricks for beginners! In this article, we’re going to show you how to change the color of an object when it is clicked in Unity. Whether you’re creating a game or another application, changing the color of objects on mouse click is a great way to add interactivity and visual interest to your scene. In this example we will be applying the script to a 3D sphere.

Here’s the code sample:

using UnityEngine;

public class ChangeColor : MonoBehaviour
{
private void OnMouseDown()
{
Renderer renderer = GetComponent<Renderer>();
renderer.material.color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
}
}
Script in action

In this script, we use the OnMouseDown method to handle the mouse click and change the color of the object. First, we use the GetComponent method to get the Renderer component of the object and store it in a Renderer variable renderer. Then, in the OnMouseDown method, we use the Renderer.material.color property to update the color of the object's material by using the Random.Range method to generate random values for the red, green, and blue channels of the color.

Here are a few ways you can enhance and optimize the script for changing object color on mouse click:

  1. Adding Multiple Colors: You can add multiple colors to the object by using an array of colors and a counter variable to cycle through the colors on each mouse click.
  2. Adding Color Transitions: You can add color transitions to the object by using the LeanTween or iTween plugins to smoothly interpolate the color of the object from one color to another over time.
  3. Adding Color Variations: You can add color variations to…

--

--

Valdarix Games

Turning my passion for video games and software development experience into a focus on video game development.