Beginning Scripts
- BakdDev

- Feb 15, 2021
- 2 min read
Due to the nature of this game project and its requirements of containing 2D minigames, which all revolve around the mouse - clicking, dragging, dropping. One of the first scripts I made was the DragAndDrop script. This was to be a versatile script with the main purpose of allowing the player with basic mouse controls suitable for a 2D environment. These could then be repurposed into multiple 2D minigames.
Using the UnityEngine.EventSystems I inherited IPointerDownHandler, IBeginDragHandler, IEndDragHandler, and IDragHandler so the scripts could detect the mouse. Each of these interfaces I have used, send a Debug.Log describing what happens, for example:
• OnPointerDown - tells me the user has clicked
• OnBeginDrag - this shows me when the user begins to drag the GameObjects
• OnDrag - prints log during the drag
• OnEndDrag - prints only when the user lets go and stops dragging
Here is the code for each:
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Pointer Down");
}public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("Begin Drag");
canvasGroup.alpha = .6f;
canvasGroup.blocksRaycasts = false;
} public void OnDrag(PointerEventData eventData)
{
Debug.Log("During Drag");
itemRectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
}public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("End Drag");
canvasGroup.alpha = 1f;
canvasGroup.blocksRaycasts = true;
}Variables and Referencing I've used:
• [SerializeField] private Canvas canvas
We use the serializeField attribute to mark our private canvas variable as serializable
• private RectTransform itemRectTransform
This is to hold the transform details of the item moving
• private CanvasGroup canvasGroup
This creates a reference to the canvas group component so we can use it in our code
Using these interfaces allow for a classic drag and drop system, think similar to cooking mama on the DS. In further posts, I'm going to show how I have adapted this code for slightly different requirements and minigames.



Comments