(Raycast2D) How to know what collider is being hit without attaching script to GameObject?

143264-owo.png

Project: Gofile - Free Unlimited File Sharing and Storage
I’m trying to make a simple cabinet that opens and closes by enabling and disabling the sprite renderer.
I couldn’t find anywhere how to do it.
Here’s my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpeningAndClosing : MonoBehaviour {

    public GameObject closedCabinet;
    public GameObject openedCabinet;

    public BoxCollider2D boxColClosed;
    public BoxCollider2D boxColOpened;



    private void Awake()
    {

        boxColClosed = closedCabinet.GetComponent<BoxCollider2D>();
        boxColOpened = openedCabinet.GetComponent<BoxCollider2D>();


    }

    private void Update()
    {
        if (closedCabinet.GetComponent<Renderer>().enabled)
        {
            openedCabinet.GetComponent<Collider2D>().enabled = false;
              
        }
        else if (closedCabinet.GetComponent<Renderer>().enabled == false)
        {
            openedCabinet.GetComponent<Collider2D>().enabled = true;
        }
        if (Input.GetMouseButtonDown(0))
        {

            Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

            RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);


            if (hit.collider.boxColClosed) || hit.collider.boxColOpened)
            {
                closedCabinet.GetComponent<Renderer>().enabled = !closedCabinet.GetComponent<Renderer>().enabled;
                openedCabinet.GetComponent<Renderer>().enabled = !openedCabinet.GetComponent<Renderer>().enabled;
            }

        }
    }
}

Thank you.

I think in your example, having a component control the interaction is exactly what you want. Since your game seems to be clicking on things and having them interact to the click - I would create an abstract interactable class where all things that do something on a click would derive from. Here is two scripts as an example:


public abstract class Interactable : MonoBehavior
{
public abstract void DoInteraction();
}

// Place on your cabinet object, hook up anims, etc
public class Cabinet : Interactable
{
    public override void DoInteraction()
    {
        // Open doors or close doors
    }
}

So here, your cabinets are an interactable class. When you raycast, just look for the interactable and if there is one… do the interaction. This is much cleaner than have your Update method doing work it shouldn’t be doing (and frankly, really shouldn’t care about doing). Here is what it would look like finding the interactable -

        Interactable interaction = hit.collider.gameObject.GetComponent<Interactable>();
        if (interaction != null)
        {
            interaction.DoInteraction();
        }


Hope this helps.