- Home /
Action when clicking on something else
I put a code on a sprite and I made it so that when you click on it it will change color. void OnMouseDown() { state = 2; GetComponent<SpriteRenderer> ().color = Color.green; }
I want it to change back when clicking on something else. How do I make something happen when clicking on something else?
Answer by mattnicholas · Jun 08, 2021 at 12:23 PM
You have to save the original color to some variable and then onMouseDown() after you change the color of the current sprite, assign the saved color to the previous sprite using the SpriteRenederer. I made this click test earlier for a client with a similar functionality. I cannot share the code here due the confidentiality thing with client but I hope you can figuire out with approach I just shared.
Answer by DenisIsDenis · Jun 08, 2021 at 10:27 AM
If relevant, then you can use a list with all objects that can be selected:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YourScript : MonoBehaviour
{
static public List<YourScript> objectsOfYourScript = new List<YourScript>();
int state = 1;
Color notSelectedColor, selectedColor = Color.green;
[HideInInspector] public SpriteRenderer mySpriteRenderer;
void Start()
{
objectsOfYourScript.Add(this);
mySpriteRenderer = GetComponent<SpriteRenderer>();
notSelectedColor = mySpriteRenderer.color;
}
void OnMouseDown()
{
for (int i = 0; i < objectsOfYourScript.Count; i++)
if (objectsOfYourScript[i] == this)
{
mySpriteRenderer.color = selectedColor;
}
else
{
objectsOfYourScript[i].mySpriteRenderer.color = notSelectedColor;
}
}
}
Your answer
Follow this Question
Related Questions
Horizontal Slider Normal-Background Change Color Independently 3 Answers
JS changing gui box color 1 Answer
change the colour of mass placed tree leaves (or make them transparent) 1 Answer
Switching color of light 1 Answer
Why Shuriken "Color Over Lifetime" doesn't affect transparent materials? 2 Answers