This a several-step answer and this is just a way of doing things, but certainly not the only one.
- Both objects and areas must have a collider component attached.
- Create the proper tags for each set to combine. In this case they're "Green" and "Purple".
- Create a layer for the areas. In this case it's "DDArea".
- Use the following script, attached to the D&D objects, as an example to your own. In this case I used spheres.
The train of thought goes as follows:
- Take advantage of the MonoBehaviour functions for handling mouse collision (OnMouseDrag and OnMouseUp) for moving the objects and detecting release, respectively.
- Move the object according to the position of the mouse.
- Cast a ray on release in order to know whether the mouse's position (thus, the object's position) is inside an area.
- If that's the case, then compare the area's and the object's tags (sets), so a decision can be made accordingly; reset the object to its initial position or increase the score.
Finally, here's my example running on Unity web player: https://dl.dropboxusercontent.com/u/4568142/unity/dragdrop/dragdrop.html
Inspector for the objects representing the areas
Inspector for the objects representing the objects (balls/spheres)
public class DragDropBall : MonoBehaviour
public Camera mainCam;
if (mainCam == null)
Debug.LogError("No camera attached");
layerMask = 1 << LayerMask.NameToLayer("DDArea");
initPosition = gameObject.transform.position;
Vector3 newPosition = mainCam.ScreenToWorldPoint(Input.mousePosition);
newPosition.z = transform.position.z;
transform.position = newPosition;
Vector3 origin = mainCam.ScreenToWorldPoint(Input.mousePosition);
Ray ray = new Ray(mainCam.ScreenToWorldPoint(Input.mousePosition), Vector3.forward);
RaycastHit hits = Physics.RaycastAll(ray, Mathf.Infinity, layerMask);
foreach (RaycastHit h in hits)
string nameSphere = gameObject.name;
string nameArea = h.collider.gameObject.name;
string tagSphere = gameObject.tag;
string tagArea = h.collider.gameObject.tag;
Debug.Log(nameSphere + " dropped on " + nameArea);
// further logic for your game here
// return the object to its inital position
gameObject.transform.position = initPosition;