It’s not - It’s storing the raycast information. What I’m using line 39 for is to get the hitData object’s transform, then get the gameobject the transform component is attatched to, then get the name of the gameobject.
hitData is probably null, you are populating it each frame and when you start dragging, it likely doesn’t hit the object you think it should. Check if hitData is null before you do anything with it.
That was it. Because I had made the sprites snap to the nearest x units, sometimes I could drag outside of the sprite, while it is still snapped to the previous position, meaning I would be over empty space, causing the raycast hitData to return null. Thanks a lot!
I’ll attach the final script below;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NEWdragdrop : MonoBehaviour {
public LayerMask IncludeLayers;//include the block layer
public LayerMask dropDataIncludeLayers;//include the valid position layer
public bool isDragging = false;
public GameObject currentBlock;
public Vector2 currentBlockPreviousPosition;
public GameObject previousBlock;
public float units = 1f;
public RaycastHit2D hitData;
void Update() {
Vector3 pointerScreenPoint = Input.mousePosition;
//screenPoint.z = Vector3.Distance(transform.position, Camera.main.transform.position);//poncey maths, just set the raycast to go forever like a boss
Vector2 pointerWorldPoint = Camera.main.ScreenToWorldPoint(pointerScreenPoint);
if (Input.GetMouseButtonDown(0)){
hitData = Physics2D.Raycast(pointerWorldPoint, Vector2.zero, Mathf.Infinity, IncludeLayers);
if (hitData) {
isDragging = true;
currentBlock = hitData.transform.gameObject;
currentBlockPreviousPosition = currentBlock.transform.position;
if (previousBlock != null) {
previousBlock.GetComponent<SpriteRenderer>().sortingOrder = 4;
}
currentBlock.GetComponent<SpriteRenderer>().sortingOrder = 5;
}
}
if (Input.GetMouseButton(0)) {
if (isDragging) {
float pointerWorldPointX = Mathf.Round(pointerWorldPoint.x / units);
float pointerWorldPointY = Mathf.Round(pointerWorldPoint.y / units);
if (hitData.transform.gameObject.name == "Block_S") {
currentBlock.transform.position = new Vector3(pointerWorldPointX + .5f, pointerWorldPointY, currentBlock.transform.position.z);
}
else if (hitData.transform.gameObject.name == "Block_A" || hitData.transform.gameObject.name == "Block_D") {
currentBlock.transform.position = new Vector3(pointerWorldPointX, pointerWorldPointY, currentBlock.transform.position.z);
}
else {
Debug.Log("There is a collider in the \'block\' layer");
}
currentBlock.GetComponent<BoxCollider2D>().enabled = false;
}
}
if (Input.GetMouseButtonUp(0)) {
RaycastHit2D dropData = Physics2D.Raycast(pointerWorldPoint, Vector2.zero, Mathf.Infinity, dropDataIncludeLayers);
if (!dropData) {
currentBlock.transform.position = currentBlockPreviousPosition;
}
isDragging = false;
currentBlock.GetComponent<BoxCollider2D>().enabled = true;
previousBlock = currentBlock;
}
}
}