How to make obj follow player when player touch it!

im not good in english, umm im try to make 2D game like player press e for keep Key and The Key is follow player and when player use to the door for open The key is gonna be gone .

To make an object follow the player when the player touches it and then disappears when the player interacts with something (like a door), you can use Unity’s scripting capabilities. Here’s a basic step-by-step guide on how to achieve this:

  1. Create the Key Object:
  • Create a 2D sprite for your key or use any GameObject as the key.
  • Add a Collider2D component to it (e.g., BoxCollider2D or CircleCollider2D) to detect collisions.
  1. Create a Player Object:
  • Create your player character (if you haven’t already) and make sure it has a Collider2D as well.
  1. Script for the Key:
  • Create a C# script, for example, “KeyController,” and attach it to your Key GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KeyController : MonoBehaviour
{
    private bool isFollowingPlayer = false;
    private Transform playerTransform;

    private void Update()
    {
        if (isFollowingPlayer && playerTransform != null)
        {
            // Move the key to follow the player's position.
            transform.position = playerTransform.position;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            // When the player touches the key, start following the player.
            isFollowingPlayer = true;
            playerTransform = collision.transform;
        }
        else if (collision.CompareTag("Door"))
        {
            // If the key touches a door (replace "Door" with the tag you use for your doors),
            // you can destroy the key or perform any other action.
            Destroy(gameObject);
        }
    }
}

oh thank you a lot.