Add highlight color feature to SpriteRenderer - c#

I have a 2D unity project for android mobiles,there are a sprite that I added button script on it
now I want use color tint on it .
Change color when I click on it
but the color not changing and I don't want do it with programming
I have tried many things, but still not working
I fixed that before with luck, but now I cant fix it again
anyone know what I am missing?

As it says in the warning, You need to specify a graphic in order to use the color tint. Try dropping in the Image component that has your button sprite here.

Based on the screenshots in your comment, you are mixing SpriteRenderer and the UI System (Image, RawImage, Button). Do not do this.
Read this to understand the difference between both. Once you decide which one to use you can do the the following below.
If you decided to use UI to display your Sprite, do this:
Create new button by going to GameObject-->UI--->Button.
If you prefer to use SpriteRenderer:
Remove any UI component such as Image, RawImage, Button from the GameObject the SpriteRenderer is attached to then manually create a highlight code. The highlight functionality is only built into the Button component. You cannot use the Button component with SpriteRenderer. You have to make your own if you prefer to use SpriteRenderer.
This is easy. Use the EventSystem. Change the color in OnPointerEnter when highlighted and back to its default color in OnPointerExit when pointer exits.
Here is a simple script to do that (Attach to the GameObject with the SpriteRenderer component):
public class SpriteDetector : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
public Color normalColor = Color.white;
public Color highlightedColor = Color.yellow;
public Color pressedColor = Color.blue;
SpriteRenderer sp;
void Start()
{
sp = GetComponent<SpriteRenderer>();
addPhysics2DRaycaster();
}
void addPhysics2DRaycaster()
{
Physics2DRaycaster physicsRaycaster = GameObject.FindObjectOfType<Physics2DRaycaster>();
if (physicsRaycaster == null)
{
Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
}
}
public void OnPointerEnter(PointerEventData eventData)
{
sp.color = highlightedColor;
}
public void OnPointerExit(PointerEventData eventData)
{
sp.color = normalColor;
}
public void OnPointerClick(PointerEventData eventData)
{
sp.color = pressedColor;
Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
}
}

Related

Unity: Make color of MeshRenderer transparent

I have a little question. I have a cube which has a Mesh Renderer and I gave it a default black material as its color. Now I would like to make the object more transparent when it touches something. I already set the Rendering Mode to Fade or Transparent. The tag is also set. This is my code:
public GameObject cube;
private Color tempcolor;
void Start()
{
tempcolor = cube.GetComponent<MeshRenderer>().material.color;
}
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Object"))
{
tempcolor.a -= 0.1f;
}
}
My code doesn't do the job. When I Debug.Log tempcolor.a it goes down but nothing happens with the cube. I also tried normal Renderer but it didn't work. Any idea?
I would be grateful if you can help me out
Kind regards
You don't need tempColor and Start() event, just save the main component temporary.
public void OnTriggerEnter(Collider other)
{
var meshRenderer = cube.GetComponent<MeshRenderer>();
if (other.CompareTag("Object"))
{
var color = meshRenderer.material.color;
color.a -= .1f;
meshRenderer.material.color = color;
}
}

Changing Tag of Collided Object Through Collision

Either the script is outdated, or it's not what I need, but I cannot find an answer to this.
To start off, I'm making a pinball styled game, whenever the ball hits a piece, it changes color, but I have multiple colored balls, and I want to lock the color in place as to not have the other balls change them (to make the game a little bit easier). I've provided a script, which may be a little too complex for a simple solution. The problem area is at the bottom with void FixedUpdate.
(I just wanna change a tag ): )
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorBlue : MonoBehaviour
{
public Material mat;
public string ballTag;
public bool reset = false;
public bool found = false;
public void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Ball" )
{
gameObject.GetComponent<MeshRenderer>().material.color = Color.blue;
reset = true;
}
}
public void FixedUpdate ()
{
if(reset)
{
GameObject.FindWithTag("Ball");
} found = true;
if(found)
{
GameObject.FindWithTag("Ball").tag = "Untagged";
}
}
}
Instead of searching for the GameObject with the "Ball" Tag which you probably have multiple off in your scene. You can rather just change the tag directly when the collision happens.
Because in the OnCollisionEnter Function you have a reference to the gameObject already, you can just use that to change the tag with collisionInfo.gameObject.tag = "Untagged".
public void OnCollisionEnter (Collision collisionInfo) {
if (collisionInfo.gameObject.CompareTag("Ball") && gameObject.CompareTag("Ball")) {
// Get Mesh Renderer of the Colided Ball Component.
var meshRenderer = collsionInfo.gameObject
.GetComponent<MeshRenderer>();
// Change Color of collided ball to be the same as the ball it collided with.
meshRenderer.material.color = gameObject
.GetComponent<MeshRenderer>().material.color;
// Set Tag to "Untagged" to make sure ball won't change color anymore
colliderInfo.gameObject.tag = "Untagged";
}
}
You could also add additional Code to change the color depending on the current Color of the gameObject. Additionaly I would advise you to use CompareTag(), which checks if the tag even exists in your scene.
If you want to get the collided gameObject you can do that with collisionInfo.gameObject.tag

Unity referencing all images in scene instead of just one

I'm trying to change the color of an image when I hover over it. It runs PointerEnter when I hover over it, and PointerExit when my mouse goes away.
Instead of changing the color of just the image I'm hovering over, it changes the color of every image in the scene. Can anybody help?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class click : MonoBehaviour {
void Start(){
}
void Update(){
}
public void PointerEnter(){
gameObject.GetComponent<Image>().material.color=new Color(1,1,0);
}
public void PointerExit(){
gameObject.GetComponent<Image>().material.color=new Color(1,1,1);
}
}
The material is shared for optimisation, it's the same one used for all the images using it.
You need to change the color of the image, simply remove material on your lines.
gameObject.GetComponent<Image>().color=new Color(1,1,0);
The Button component has transition settings where you can set colors for state, maybe you dont need the extra code.
Unity has 2 pre-programmed functions called OnMouseOver() and OnMouseExit(). Which you can use to see if the mouse entered your Image.
You would need to add this Code Snippet to each Image you want the Color to be changed on Hover and make sure that you get the .Color Component instead of the .material.color Component.
Example:
public class OnMouseOverExample : MonoBehaviour
{
void OnMouseOver() {
// Executes when you Hover over this GameObject with the Mouse
gameObject.GetComponent<Image>().color = new Color(1f, 1f, 0f);
}
void OnMouseExit() {
// Executes when you no longer Hover over this GameObject with the Mouse
gameObject.GetComponent<Image>().color = new Color(1f, 1f, 1f);
}
}
If you want to change a UI Components Color, you could also use the Button Component. Which already has functionality built in, you can use to tint the Color of your Image.

Trying to change color with a script in Unity - SpriteRenderer.color doesn't work

i'm a new to unity and trying to change a sprite's color through a script.
i'm following this tutorial page: https://www.tutorialspoint.com/unity/unity_coroutines.htm. i'm using Unity 2019.2.0f1
when pressing "play" i can see the colors changing every second in the inspector, but nothing happens in the scene
the code:
public class colorChanger : MonoBehaviour
{
public int seconds_interval;
public SpriteRenderer sr;
public Color color_1;
public Color color_2;
IEnumerator changeColor(){
while (true){
if (sr.color == color_1){
sr.color = color_2;
} else {
sr.color = color_1;
}
yield return new WaitForSeconds(seconds_interval);
}
}
// Start is called before the first frame update
void Start()
{
sr = gameObject.GetComponent<SpriteRenderer>();
StartCoroutine( changeColor() );
//sr.color = color_1;
}
// Update is called once per frame
void Update()
{
}
}
explanation and screenshots:
this is the sprite, notice it starts as purple, then the script should change it's color:
https://i.ibb.co/rQy2Lpr/1.jpg
when pressing "play" i can see the colors changing every second in the inspector, but nothing happens in the scene:
yellow:
https://i.ibb.co/DRhcpPT/2.jpg
green (after 1 second):
https://i.ibb.co/Yc0v26K/3.jpg
actually, the inspector is totaly ignored by the scene! notice that the sprite is white (and not purple/yellow/green).
notice that if i change the scale nothing happens in the "play" screen:
https://i.ibb.co/sjdCvfw/4.jpg
but when i go back to "game" screen (without stopping the game), the frame of the sprite changes but not it's actual size:
https://i.ibb.co/R054Rv0/5.jpg
it looks like the script is making the inspector disconnect from the scene.
is it a bug? or am i missing something here?
thank you :)
solved!
my problem was that: I have chosen colors in the UI interface while their Alpha property was 0.
so i couldn't see any color changing.
I still don't understand why the "scale" property wasn't reacting to live changes in the inspector, but choosing colors with Alpha of 255 (opacity) solved everything.

Unity, changing spite onMouseEnter / onMouseExit to another sprite [duplicate]

This question already has answers here:
How to detect click/touch events on UI and GameObjects
(4 answers)
Closed 5 years ago.
Hi as you can tell i am incredibly new to unity.
I just want a sprite to change to a different image when the mouse enters or leaves the sprite. Example, when hovering over a play button, it changes to a slightly different coloured sprite.
Thanks
Here is what i tried
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseOver : MonoBehaviour
{
public Sprite sprite1; // Drag your first sprite here
public Sprite sprite2; // Drag your second sprite here
private SpriteRenderer spriteRenderer;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer.sprite == null)
spriteRenderer.sprite = sprite1;
}
void OnMouseEnter()
{
ChangeSprite();
}
void OnMouseExit()
{
ChangeSprite();
}
void ChangeSprite()
{
if (spriteRenderer.sprite == sprite1)
{
spriteRenderer.sprite = sprite2;
}
else
{
spriteRenderer.sprite = sprite1;
}
}
}
I would prefer to use UI Button with Image component. It has transition property where you can use different sprites on different states (normal, hover, pressed and disabled states).
Just use Button component and set transition mode to SpriteSwap:
Button Transition property should look like this:
As Default button object has image in a child component which is set to Target Graphic, you can set sprite1 as image source by default and use sprite2 as Highlighted Sprite.
This would work perfectly without using any code.
Hope this helps :)
Your sprite needs a collider attached to it in order for the OnMouseEnter() event to fire.

Categories

Resources