Search code examples
unity-game-engine2dspriteunity3d-2dtools

How to change a sprite to another and then back after 1 second


I'm developing a simple game in Unity2D, in which several monsters eat things that are dragged to them. If the right object is dragged to the monster, the score goes up by one and the monster should make a happy face, otherwise, score goes down and makes a sad face. This is the code I'm using for that (minus the transitions to happy/sad):

 if (transform.name.Equals ("yellow")){

        if (collinfo.name.Equals ("plastic(Clone)")) {
            Debug.Log ("+1");
            audio.Play ();
            GameSetup.playerScore += 1;
            gs.GetComponent<GameSetup>().removeit(aux);             
        } 
        else {
            Debug.Log ("-1");
            audio.Play ();
            if (GameSetup.playerScore == 0)
            {}
            else
            {
            GameSetup.playerScore -= 1;
            }
            gs.GetComponent<GameSetup>().removeit(aux);
        }

The audio played is just a 'munching' sound.

I want the monster to change sprites to happyFace (via GameObject.GetComponent ().sprite = happyFace), wait one second and then switch back to it's normal sprite, but don't know how to implement that waiting period.

Any and all help would be much appreciated.


Solution

  • This can be implemented several ways, however, I would use a method that returns an IEnumerator like so…

    This assumes you have a variable in your script that has a reference to the SpriteRenderer that is attached to the GameObject with this script.

    SpriteRenderer sr = GetComponent <SpriteRenderer> ();
    

    I also assume you have an original sprite and the possible sprites to change to as variables too.

    public Sprite originalSprite;
    public Sprite happyFaceSprite;
    public Sprite sadFaceSprite;
    
    public IEnumerator ChangeFace (Sprite changeToSprite)
    {
        sr.sprite = changeToSprite;
        yield return new WaitForSeconds (1.0f);
        sr.sprite = originalFaceSprite;
    }
    

    You would then call this function with the applicable sprite as the variable.

    if (happy)
        StartCoroutine (ChangeFace (happyFaceSprite);
    else
        StartCoroutine (ChangeFace (sadFaceSprite);
    

    Because the ChangeFace method returns an IEnumerator, we must call that function with the StartCoroutine function. The method will run until it reaches the yield return new WaitForSeconds (1.0f) function, then wait for 1.0f seconds and then resume where it stopped last time.

    Understand?

    Note I haven't tested this but I don't see why it wouldn't work.