I’ve been following an online tutorial where Ui Components are dragged by implementing the IDragHandler interface but when I tried to apply it to a non UI gameObject it’s not working, is there a way to make it work and any helpful tutorials on the subject?
You can.
You need to set up your eventsystem accordingly however.
To do this you need 2 things.
- An EventSystem
- A raycaster (A canvas uses a GraphicRaycaster, but you can also use Physics2DRaycaster or PhysicsRaycaster).
To make your object respond to events, simply add a PhysicsRaycaster to your camera, make sure you have an eventsystem somewhere in the scene, and that your MonoBehaviour implements IDragHandler (and make sure it has a collider obviously).
As for how to implement dragging, this is a simplified piece of code that allows you to drag in world x/z.
using UnityEngine;
using UnityEngine.EventSystems;
public class DragExample : MonoBehaviour, IDragHandler
{
public void OnDrag(PointerEventData eventData)
{
// Vector3.up makes it move in the world x/z plane.
Plane plane = new Plane(Vector3.up, transform.position);
Ray ray = eventData.pressEventCamera.ScreenPointToRay(eventData.position);
float distamce;
if (plane.Raycast(ray, out distamce))
{
transform.position = ray.origin + ray.direction * distamce;
}
}
}
No, you’ll have to write up your own code structure.