Search Unity

Changing Sprite in Script

Discussion in '2D' started by Tetracube, Jan 10, 2014.

  1. Tetracube

    Tetracube

    Joined:
    Jan 7, 2014
    Posts:
    7
    I have an object (TestObj) and I want to change its sprite from sprite1 to sprite2 when it's clicked on. How would I code that in C#?
     
  2. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,051
    Place both sprites in the gameobject and then turn them on/off as needed with SetActive();
     
  3. Tetracube

    Tetracube

    Joined:
    Jan 7, 2014
    Posts:
    7
    I'm not entirely sure how to do that.
     
  4. Dave-xP

    Dave-xP

    Joined:
    Nov 8, 2013
    Posts:
    106
    You want to do this?
    Code (csharp):
    1.  
    2.     public Sprite sprite1, sprite2; // Sprites
    3.     private SpriteRenderer spriteRenderer;
    4.  
    5.     void Start () {
    6.         spriteRenderer = gameObject.GetComponent<SpriteRenderer> ();
    7.     }
    8.  
    9.     void OnMouseDown () {
    10.         if (spriteRenderer.sprite == sprite1) {
    11.             spriteRenderer.sprite = sprite2;
    12.         } else {
    13.             spriteRenderer.sprite = sprite1;
    14.         }
    15.     }
    16.  
     
    Last edited: Jan 11, 2014
  5. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,051
    Create a new game object.
    Drag your sprites into that gameobject in the hierarchy.
    $Screen Shot 2014-01-10 at 8.06.44 PM.png
    Create a script along these lines:
    Code (csharp):
    1.  
    2. public class ClickToChange : MonoBehaviour {
    3.  
    4.     public GameObject sprite_1;
    5.     public GameObject sprite_2;
    6.  
    7.     void Awake()
    8.     {
    9.         // just to ensure a clean start.
    10.         sprite_1.SetActive(true);
    11.         sprite_2.SetActive(false);
    12.     }
    13.  
    14.     void OnMouseDown()
    15.     {
    16.         sprite_2.SetActive(!sprite_2.activeSelf);
    17.         sprite_1.SetActive(!sprite_1.activeSelf);
    18.     }
    19. }
    20.  
    You can then place your script and collider on that game object, and the add the references in the inspector.
    $Screen Shot 2014-01-10 at 8.16.00 PM.png

    Not very fancy, but will do the trick.

    Cheers.
     
  6. Tetracube

    Tetracube

    Joined:
    Jan 7, 2014
    Posts:
    7
    Oh! I completely forgot that I could do that despite doing a tutorial on it whoops

    Thanks.