- Home /
Change a Sprite when clicked?
Been stuck on this for ages! Im wondering how to make a 2D Sprite change texture when it is clicked (Inside it's collider). Then I need to to change back to it's old texture when you click elsewhere. It's probably quite simple but I can't seem to work it out, any help will be appreciated!
Answer by slek120 · Apr 05, 2014 at 12:29 PM
using UnityEngine;
using System.Collections;
public class SpriteSwitch : MonoBehaviour
{
public Sprite oldSprite;
public Sprite newSprite;
SpriteRenderer spriteRenderer;
void Start ()
{
spriteRenderer = GetComponent<SpriteRenderer> ();
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
Vector3 mousePos = Input.mousePosition + Vector3.forward * Vector3.Distance (transform.position, Camera.main.transform.position);
Vector3 worldPos = Camera.main.ScreenToWorldPoint (mousePos);
Vector2 testPos = new Vector2 (worldPos.x, worldPos.y);
if (collider2D.OverlapPoint (testPos)) {
spriteRenderer.sprite = newSprite;
} else {
spriteRenderer.sprite = oldSprite;
}
}
}
}
One caveat, when the sprite changes, the collider still stays the same.
I get this error: NullReferenceException: Object reference not set to an instance of an object SpriteSwitch.Update () (at Assets/Scripts/$$anonymous$$isc/SpriteSwitch.cs:19)
hmm. That's funny. $$anonymous$$aybe it's the Camera.main. Do you have a camera that is tagged as "$$anonymous$$ainCamera"?
I have 2 cameras at the moment. One is my main one, the other is the $$anonymous$$imap. The $$anonymous$$imap camera is just called $$anonymous$$inimap, my main one is just called Camera. Below is the properties of my main camera.
At the top of the inspector, there is a "Tag" set to "Untagged". Change that to "$$anonymous$$ainCamera". Either that, or in the script, add "public Camera mainCamera" and link the camera in the inspector. Then replace "Camera.main" with "mainCamera".
Thank you so much, it works perfectly! Exactly what I wanted :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613141957im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Looking for: Simple pathfinding in 2D Tower Defense game with no objects to collide with? 1 Answer
Collision2D compare the y axis of the object colliding with the object being collided with 0 Answers
How to add ParticleSystem in point where CollisionTrigger2D touch another? 1 Answer
Cannot move Polygon Collider 2D vertices in one project 0 Answers
Rigidbody2D Player collider seems larger than displayed 0 Answers