rojert
rojert

Reputation: 11

How to detect when an object stops colliding?

How do I stop being to interact when I stop colliding with an object? This script is added to a chest in Unity (2d). I can walk around, press E, nothing happens, then when I collide with the chest I am able to interact with it anywhere. I just started c# recently.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Unity.VisualScripting;
using UnityEngine;

public class CollidableObject : MonoBehaviour
{
    private bool z_Interacted = false;
    private Collider2D z_Collider;
    private bool colliding = false;
    

    protected virtual void Start()
    {
        
    }

    

    private void OnCollisionStay2D(Collision2D collision)
    {
        
        if (collision.gameObject.name == "Player")
        {
            colliding = true;
            Debug.Log("test");
        }

        else if (collision.gameObject.name != "Player")
        {
            colliding = false;
        }
    }

    
    
protected virtual void Update()
    { 
        if (Input.GetKey(KeyCode.E))
        {
            if (!z_Interacted)
            {
                if (colliding)
                {
                    Debug.Log("INTERACT WITH " + name); 
                    z_Interacted = true;
                }
            }
            
        }
    }
    

    
}

Upvotes: 0

Views: 148

Answers (1)

Vlad Stoyanoff
Vlad Stoyanoff

Reputation: 163

Have you tried OnCollissionExit?

Upvotes: 4

Related Questions