- Home /
Change sprite when click on particular sprite
So I want to change particular sprite when it's clicked, i already attach collider on that sprite. At first i want to use update function (script below), but it didn't work. so I try onMouseDown function, but it still won't change. is there something I miss? or is my code wrong?
using UnityEngine;
using System.Collections;
public class ChangeSprite : MonoBehaviour {
public Sprite girl, boy;
private SpriteRenderer spriteRenderer;
void Start() {
spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
spriteRenderer.sprite = boy;
}
// void Update () {
// if (Input.GetMouseButtonDown (0)) {
// Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// RaycastHit hit;
// if (Physics.Raycast (ray, out hit)) {
//
// if (hit.collider.tag == "student") {
// spriteRenderer.sprite = girl;
// }
// }
// }
// }
void onMouseDown(){
spriteRenderer.sprite = girl;
}
}
Hi, I would recommend you put a Debug.Log("clicked"); in your On$$anonymous$$ouseDown funciton to first check if the click is registering.
Answer by Rajeesh_AR · Mar 29, 2016 at 09:00 AM
Hi @eevachan,
I tried and got the result. You first check whether the box collider is as large as the image.
I coded the below scipt:
public class ChangeSprite : MonoBehaviour {
public Sprite sp1,sp2;
SpriteRenderer sr;
// Use this for initialization
void Start ()
{
sr = gameObject.GetComponent<SpriteRenderer> ();
}
void OnMouseDown()
{
if (sr.sprite.Equals (sp1))
sr.sprite = sp2;
else
sr.sprite = sp1;
}
}
In this initially I drag and drop one sprite to the inspector window. Also note the function is "OnMouseDown () " .. "O" is capital letter
The script above toggles between the images on mouse click.. Hope this will help you..