How to make a sprite clickable?

MIke picture MIke · Jan 26, 2015 · Viewed 20.4k times · Source

I have googled plenty and only come up with really complicated methods of doing it. I also found the function OnMouseDown() but I haven't been able to make it work.

At the moment the sprite activates when you tap anywhere on screen.

EDIT - Yes it has a 2d Box collider

My code below:

using UnityEngine;
using System.Collections;

public class mute : MonoBehaviour 
{
    public bool isMuted = false;
    public Sprite mute1, mute2;

    private SpriteRenderer spriteRenderer; 

    private void Start () 
    {
        spriteRenderer = GetComponent<SpriteRenderer>();

        if (spriteRenderer.sprite == null) 
            spriteRenderer.sprite = mute1;
    }
    private void Update () 
    {
        if (Input.GetKeyDown (KeyCode.Mouse0)) 
        {
            if (!isMuted)
            {
                AudioListener.pause = true;
                AudioListener.volume = 0;

                isMuted = true;
                ChangeSprite();

            }
            else
            {
                AudioListener.pause = false;
                AudioListener.volume = 1;

                isMuted = false;
                ChangeSprite();
            }
        }
    }
    private void ChangeSprite() => spriteRenderer.sprite = 

spriteRenderer.sprite == mute1 ? mute2 : mute1; }

Answer

maZZZu picture maZZZu · Jan 26, 2015

Using OnMouseDown

The easiest method is to add this function into any script component attached to the gameObject containing the sprite:

void OnMouseDown(){
    Debug.Log("Sprite Clicked");
}

The gameObject also need to have a collider. Both 2D and 3D colliders work.

Comparison to other methods

Raycasting only works on one collider type at the time Physics.Raycast works only against 3D colliders and Physics2D.Raycastworks only against 2D colliders. OnMouseDown works on both, but it is possible that its performance is as bad as the performance of executing both of the raycasts.

Position based methods stated in other answers are good for performance. Couple of if statements is much faster to compute than ray casting, but ray casting is still fast enough for basic scenes. The disadvantage of the position checks is that if you change anything (scale or position) you are likely to break your if clauses. Also the ifs are quite complicated if you want sprites to be on top of each other.