W
W
Wadim_wadim20002020-05-27 11:52:45
C++ / C#
Wadim_wadim2000, 2020-05-27 11:52:45

Unity 2D C# - how to open the panel only when entering the collider by the button?

I watched a YouTube tutorial on how to make an inventory in unity. Everything suits me there, but the only problem is that there the "storage" (a chest in which you can put items from the inventory) is "opened" using raycast. And a lesson on a 3d game, but I have 2d. I just need it to be able to open only when entering the player's collider. Thanks in advance, I'll attach the code below:

void Update()
    {
        Storage storage = storageInstance();
        if (storage)
        {
            if (Input.GetKeyDown(Inventory.instanceInventory.openKey))
            {
                Inventory.instanceInventory.storagePanel.SetActive(true);

                if(Inventory.instanceInventory.storageName)
                    Inventory.instanceInventory.storageName.text = storage.storageName;

                Inventory.instanceInventory.inventoryPanel.SetActive(true);
                DisplayItems();
            }

            if (Input.GetKeyDown(Inventory.instanceInventory.closeKey))
            {
                Inventory.instanceInventory.inventoryPanel.SetActive(false);
                Inventory.instanceInventory.storagePanel.SetActive(false);
            }
        }

    }

here, as it were, a storage panel opens with cells by pressing a button.
public static Storage storageInstance()
    {
        Ray ray = Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, Inventory.instanceInventory.openDistance))
        {
            if (hit.collider.GetComponent<Storage>())
                return hit.collider.GetComponent<Storage>();
        }
        return null;
    }

and here it is checked whether the chest is too far from the player, and if not, then it can be opened.
Here's how to make it so that instead of raycast it could be opened when entering the collider?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DanielMcRon, 2020-05-27
@Wadim_wadim2000

If it is necessary that the touch opens OnCollisionEnter2D. If from the entrance to the chest area, then you can put the 2nd collider on the ship, check the IsTrigger box and process it with the OnTriggerEnter2D method, and then simply write the object to that variable. In Update check if the reference is null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question