0

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;
                }
            }
            
        }
    }
    

    
}
rojert
  • 11

1 Answers1

4

Have you tried OnCollissionExit?

  • 1
    I have, I don't really know what to put inside of it to work. I think it has to do with the fact that I'm also colliding with the ground. NVM GOT IT – rojert Sep 21 '22 at 18:27
  • it works by default, you don't have to do anything extra. Just put your logic in. In this case: colliding = false. Try it and let me know how it goes. – Vlad Stoyanoff Sep 21 '22 at 18:31