K
K
KeysCG2022-04-05 23:31:07
Unity
KeysCG, 2022-04-05 23:31:07

Why is the object not returned to the cell?

Good day!
Please tell me why the prefab does not want to get into a cell in a given area?
I've already broken my head and I can not understand what the trouble is.
I have slots where prefabs (item) are stored in the inventory and there is an area on which this script weighs (when releasing the item in this area should become in the cells specified in slotsInventory):

using UnityEngine;
using UnityEngine.EventSystems;

public class ItemDropInventory : MonoBehaviour, IDropHandler
{
    public Transform slotsInventory;
    public void OnDrop(PointerEventData eventData)
    {
        if (eventData.pointerDrag != null)
        {
            eventData.pointerDrag.transform.SetParent(slotsInventory);
        }
    }
}


This hangs on the item itself:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ItemDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    RectTransform rectTransform;
    Canvas canvasInventory;
    Button itemButton;

    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        itemButton = GetComponent<Button>();
        canvasInventory = GetComponentInParent<Canvas>();
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
        rectTransform.SetParent(canvasInventory.GetComponent<RectTransform>());
        itemButton.enabled = false;
    }
    public void OnDrag(PointerEventData eventData)
    {
        rectTransform.anchoredPosition += eventData.delta / canvasInventory.scaleFactor;
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        itemButton.enabled = true;
    }
}

And my item just stops at the place where I release it :(
Sometimes if you click on the item many times or move it in some places, it works and it disappears into the cell. That is, it seems to work every other time :(

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question