Search code examples
unity-game-enginespritecollision

Sprite not updating on collision


Can someone explain why this code is not working as intended? Currently if there is a collision the sprite (flag) changes to green. The debug statements are working as I would expect but the sprite (flag) is not changed back to red in the event of no collision.

public Sprite gflag;
public Sprite rflag;
public SpriteRenderer render;
public GameObject Player;
private Checkpoint checkpoint;
private bool hit = false;

void Update()
{
    if(hit != true)
    {
        Debug.Log("False!");
        render.sprite = rflag;
    }
}

// Modify color of flag depending on collision
void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.gameObject.tag == "Player")
    {
        Debug.Log("True!");
        render.sprite = gflag;
        hit = true;
    }
}

Here is a screen shot of the checkpoint prefab:

enter image description here


Solution

  • Have you considered moving the logic in the Update() function to a OnTriggerExit2D function?

    public Sprite gflag;
    public Sprite rflag;
    public SpriteRenderer render;
    public GameObject Player;
    private Checkpoint checkpoint;
    private bool hit = false;
    
    // Modify color of flag depending on collision
    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.tag == "Player")
        {
            Debug.Log("True!");
            render.sprite = gflag;
            hit = true;
        }
    }
    
    // Modify color of flag depending on collision
    void OnTriggerExit2D(Collider2D collider)
    {
        if (collider.gameObject.tag == "Player")
        {
            Debug.Log("False!");
            render.sprite = rflag;
            hit = false;
        }
    }
    

    This way, instead of checking in Update every frame, it will be handled within the collision functions entirely.

    EDIT: To answer your initial question, the reason the code was not updating the flag back to red in the case of no collision is because you were not setting the hit boolean to false once the collision was exited.