Rob Acuña
Rob Acuña

Reputation: 35

How to switch sprites when a collision occurs?

First: I´m totally new with programming and this must be an easy task so I hope you can help me to fix this while I learn from your approximation to this so maybe I can solve future problems in my beginner project.

So I´m trying to make a gameobject to change its sprite when it collides with another one. In the code you can see that I made the CandleLit and CandleUnlit with public properties so I dragged the corresponding sprites to their respective slot in the Inspector in Unity... the idea is that when the CandleUnlit collider touches the collider of my object with tag "Smallfire" it switch the sprite of CandleUnlit to the sprite of CandleLit... I don´t have errors in console but nothing is happening when the collision occurs so I know it must be a very stupid problem whit the way I understand the scripting flow... so I hope someone can help me to find what i´m missing or what did I do wrong. Thanks in advance I will check my tutorials while waiting for someone´s help because I can´t figure it out after many hours by my self :(

public class CandleSpriteSwitch : MonoBehaviour
{
    public Sprite CandleLit;
    public Sprite CandleUnlit;

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "SmallFire")
        {
            gameObject.GetComponent<SpriteRenderer>().sprite = CandleLit;
        }
        else
        {
            gameObject.GetComponent<SpriteRenderer>().sprite = CandleUnlit;
        }
    }
}

Upvotes: 1

Views: 2056

Answers (2)

Nikola G.
Nikola G.

Reputation: 335

As @Zohaib Zaidi mentioned in collisions there must be at least 1 Rigidbody in order to work properly. If you have rigidbody and sizes of 2 colliders are adjusted correctly and are not set to "is Trigger". Then the only reason could be in Layer Collision Matrix, if that's fine, then there is no reason for it to not work!

public class CandleSpriteSwitch : MonoBehaviour
{
    public Sprite candleLit;
    public Sprite candleUnlit;
    public SpriteRenderer render;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.CompareTag("SmallFire"))
        {
            render.sprite = candleLit;
        }
        else
        {
            render.sprite = candleUnlit;
        }
    }
}

Btw.. when declaring a name variable always use a lowercase for the first word. In general this shouldn't be a problem but it will for sure create difficulties later on. Plus, you could actually declare Sprite Renderer on the beginning and not when collision occurs.

Upvotes: 1

Zohaib Zaidi
Zohaib Zaidi

Reputation: 298

One of your GameObject needs to have a BoxCollider2D and a Rigidbody2D. Collisions do not take place until and unless a rigidbody2d is present. So in your case just make sure the 2 GameObjects that are colliding have a Rigidbody2D and a Collider2D

Upvotes: 1

Related Questions