Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Sprite Change on Mouse Click

Discussion in 'Scripting' started by Magz-Studios, Apr 15, 2015.

  1. Magz-Studios

    Magz-Studios

    Joined:
    Apr 9, 2015
    Posts:
    5
    I am trying to make a button that once it is clicked it changes to another sprite. Then when it is clicked again it changes to the sprite it was in the beginning. Here is my code as of now:

    Code (CSharp):
    1.  
    2. usingUnityEngine;
    3. usingSystem.Collections;
    4. publicclass mute :MonoBehaviour{
    5. publicSprite unmuted;
    6. publicSprite muted;
    7. voidOnMouseDown()
    8. {
    9. if(this.gameObject.GetComponent<SpriteRenderer>().sprite == unmuted)
    10. {
    11. this.gameObject.GetComponent<SpriteRenderer>().sprite = muted;
    12. }
    13. if(this.gameObject.GetComponent<SpriteRenderer>().sprite == muted)
    14. {
    15. this.gameObject.GetComponent<SpriteRenderer>().sprite = unmuted;
    16. }
    17. }
    18. }
    19.  
    If am pretty new to unity and C# so any help will be appreciated. Thanks!
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    You're on the right track, just a small logic problem. You want to use "else if" instead of "if" for the second statement.

    Code (csharp):
    1.  
    2. if(case)
    3. {
    4.  
    5. }
    6. else if(case)
    7. {
    8.  
    9. }
    10.  
    What's happening right now is you're setting the sprite to muted, then immediately checking if the sprite is muted and setting it right back to unmuted.

    I would also strongly consider caching the result of the GetComponent<> call so you don't have the performance hit of retrieving the component four times.

    Your final code would look something like:

    Code (csharp):
    1.  
    2. void OnMouseDown()
    3. {
    4.      SpriteRenderer spriteRenderer = this.gameObject.GetComponent<SpriteRenderer>();
    5.  
    6.      if(spriteRenderer.sprite == unmuted)
    7.           spriteRenderer.sprite = muted;
    8.      else if(spriteRenderer.sprite == muted)
    9.          spriteRenderer.sprite = unmuted;
    10. }
    11.  
     
    Magz-Studios likes this.
  3. Magz-Studios

    Magz-Studios

    Joined:
    Apr 9, 2015
    Posts:
    5
    Thanks so much! I will try that ASAP!