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…

--

--

Valdarix Games
Valdarix Games

Written by Valdarix Games

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

No responses yet