Fix: Read AnimalMan’s answer
I’m making a drag and drop system for my game, but when I drag the object it constantly gets closer to the camera until it teleports back to where it should be and repeats the process. I’m doing all this in 3D just so you know.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragAndDrop : MonoBehaviour
{
[SerializeField] private Button placeRockWall;
[SerializeField] private GameObject[] defenses;
[SerializeField] private GameObject shopUI;
[SerializeField] private Camera cam;
private enum Structures {none, rockWall};
private Structures structures = new Structures();
private GameObject rockWallCopy;
[SerializeField] private Transform buildings;
void Update()
{
if (Input.GetMouseButton(0))
{
if (EventSystem.current.currentSelectedGameObject.CompareTag("Place Rock Wall") && structures == Structures.none)
{
Place(defenses[0], Structures.rockWall);
}
}
if (Input.GetMouseButtonUp(0) && structures != Structures.none)
{
shopUI.SetActive(true);
structures = Structures.none;
}
}
void LateUpdate()
{
if (structures == Structures.rockWall)
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit))
{
rockWallCopy.transform.position = raycastHit.point;
}
}
}
void Place(GameObject objectToPlace, Structures whatObjectIs)
{
Debug.Log("Placing");
shopUI.SetActive(false);
if (whatObjectIs == Structures.rockWall)
{
Debug.Log("Object is rock wall, instantiating copy");
rockWallCopy = Instantiate(defenses[0], buildings);
}
structures = whatObjectIs;
}
}