In my game I am trying to have numbered blocks and math operators be able to be dragged down into their respectively color coded holders (white holders = Numbers, black holders = operations). The spawn in color coded blocks called spawners. If you drop a block you were dragging in a space that isn't a holder, then the block would immediately snap back to its respective spawner.
However, I am now encountering this issue where 99% of the time when I drop the block onto its respective holder, the block snaps back to its spawner instead of staying there.
Here's the minimum reproducible code for dragging the blocks:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
[RequireComponent(typeof(Collider2D))]
public class DragDrop : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
[SerializeField] private SpriteRenderer _spriteRenderer;
public SpriteRenderer _SpriteRenderer => this._spriteRenderer;
[HideInInspector]public static bool isInSpace;
[HideInInspector]public Vector3 initialPos;
private void Start()
{
initialPos = transform.position;
isInSpace = true;
}
public void OnDrag(PointerEventData eventData)
{
if (isInSpace == false)
{
Vector3 movement = new Vector3(
x: (eventData.delta.x/3) * Time.deltaTime,
y: (eventData.delta.y/3) * Time.deltaTime);
this.transform.localPosition += movement;
}
}
public void OnBeginDrag(PointerEventData eventData)
{
isInSpace = false;
}
public void OnEndDrag(PointerEventData eventData)
{
if (isInSpace == false)
{
transform.position = initialPos;
}
}
#if UNITY_EDITOR
private void Reset()
{
this._spriteRenderer = this.GetComponent<SpriteRenderer>();
}
#endif
}
And Here's the code for receiving the blocks:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class RecieveBlock : MonoBehaviour, IDropHandler
{
public void OnDrop(PointerEventData Block)
{
if (Block.pointerDrag != null && Block.pointerDrag.tag == gameObject.tag)
{
Block.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
DragDrop.isInSpace = true;
}
}
}
I have no idea why it doesn't set off the isInSpace bool to be true and stay there.
Heirarchy Image For Number Blocks:
Heirarchy Image For Operation Blocks:
Heirarchy Image For Holder Blocks:
Thank you for reading.