Tutorial: Spawn Items by Drag From Menu

NOTE: This tutorial works with version 1.7+ of the Mobile Touch Camera asset.

The following topic is about spawning Pickable Items by dragging them out from a menu and into the scene. A popular example for a game that offers this kind of item spawning is Hay Day from Supercell.

For this tutorial I am assuming that you have created either a Button or an Image using the UnityUI system. First you need to add the “Event Trigger” component to the button or image you want to drag items out of. After that you have to click the “Add New Event Type” button and select “Pointer Down”. Next hit the “+” to add an empty entry to the Event Trigger. For the target of this event you have to create a new method somewhere on a MonoBehaviour. Ideally you’ll have some kind of Item Controller script that you can use to handle this event and also the callbacks from the camera asset. For this demo I have created a MonoBehaviour called SpawnDemoController that I placed on the Main Camera object. In this controller I added the method SpawnNewItemAndStartDrag and selected it as the Event Trigger method. Now the event trigger on my image object looks as follows:

tutorial_spawn_item_from_menu

The method I created looks as follows:

public void SpawnNewItemAndStartDrag() {

  //Spawn item and fetch its collider component.
  GameObject spawnedGO = GameObject.Instantiate(prefabToSpawn);
  Collider itemCollider = spawnedGO.GetComponent<Collider>();

  //Set the spawned item to the position of the finger in the scene.
  spawnedGO.transform.position = mobilePickingController.GetFinger0PosWorld();

  //Trigger the drag request.
  mobilePickingController.RequestDragPickable(itemCollider);
}

For this to work there are a few things to note. First, you need to have a reference in your script to the prefab you want to spawn. In the above the reference is called prefabToSpawn. This prefab must have a Collider component as well as the Mobile Touch Pickable component attached. Next you also need to have a reference to the Mobile Picking Controller. In the above this references is called mobilePickingController.

With this in place the defined prefab should be spawned as soon as you hold your finger down on the image or button and it should be placed right under your finger and follow your move.

When releasing your finger the On Pickable Transform Move Ended event will be invoked by the Mobile Picking Controller. Using this Unity Event you should set up a callback that allows you to check if the item has been dragged onto a valid position in your scene. If it isn’t dragged onto a proper position you may want to delete the spawned item using the GameObject.Destroy call.

Advertisements