Reputation: 51
I am making a game which involves a lot of drag and drop. I have some objects that the player has to drag into the object slot. How do I destroy the object if the player drags it outside the slot or somewhere randomly on the canvas. This is the code I have used.
public class dragDrop : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler { Image image; CanvasGroup canvasGroup; Vector2 initPosition; void Awake(){ Time.timeScale = 1; image = GetComponent<Image>(); canvasGroup = GetComponent<CanvasGroup>(); initPosition = transform.position; } public void OnBeginDrag(PointerEventData eventData) { canvasGroup.alpha = 0.5f; canvasGroup.blocksRaycasts = false; } public void OnDrag(PointerEventData eventData) { transform.position = eventData.position; } public void OnEndDrag(PointerEventData eventData) { canvasGroup.alpha = 1f; canvasGroup.blocksRaycasts = true; } }
Upvotes: 1
Views: 174
Reputation: 26
Here is your answer.
https://answers.unity.com/questions/889220/unity-46-ui-canvas-width-height.html
Perhaps, you need to destroy an object, that is outside the player's camera? In this case, use the code Screen.width
and .height
If you need to destroy an object, that is not included in the slot, then you need to create this area. There are many tutorials on the internet, like "how to create borders, around an area". Use one of them, what do you need in your case.
Separately from myself, I advise that it be smooth, with considering the size of the dragged object itself. So that it is not destroyed immediately, as it enters the field of destruction, but perhaps more smoothly, when last part of the object, has enter in that area. As an option, with the launch of the script, for a smooth destruction. (DOTween as an option, for different types of smoothness). Use IEnumerator
, and like that multithreading in script, to control this process.
Upvotes: 1