I have a script so that you can simply click and drag around objects with the mouse. When I create a 2d Object sprite, using a simple square, it works. However when I try and use the script on an image or textobject or even a canvas object it does not work. I don’t understand why. All objects have boxcolliders2d components.
Here is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveIt : MonoBehaviour{
private bool _dragging;
private Vector2 _offset;
void Update(){
if(! _dragging) return;
var mousePosition = GetMousePos();
transform.position = mousePosition - _offset;
}
void OnMouseDown(){
_dragging = true;
_offset = GetMousePos() - (Vector2)transform.position;
}
void OnMouseUp(){
_dragging = false;
}
Vector2 GetMousePos(){
return Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
As a separate reply, you shouldn’t be modifying the Transform if you’re using 2D physics. You should be using a Rigidbody2D and its API to cause movement of colliders etc. Doing what you’re doing causes those BoxCollider2D to be completely recreated each time you modify the Transform because they are Static (non-moving) without a Rigidbody2D.
It’s not the same question… And it’s a different script. First question was about coordinates, this one about something not working. I hope I am allowed to ask several questions on the same topic.
I recommend using IPointerEnterHandler for UI elements. Adding colliders to UI doesnt seem appropriate since you should never really “collide” with them and a scene object.