behzad
behzad

Reputation: 857

Add highlight color feature to SpriteRenderer

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?

here is my properties

Upvotes: 1

Views: 1704

Answers (2)

Programmer
Programmer

Reputation: 125245

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);
    }
}

Upvotes: 1

Kashif Siddiqui
Kashif Siddiqui

Reputation: 1546

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.

Upvotes: 2

Related Questions