How do I instantiate a UI image at touch position?

The game is top-down 2D with the camera fixed on the player as they move around the map.

We want to have an indicator of where the last touch position was, which seems to mean having the indicator as a prefab, instantiating it on finger press and then transforming it correctly:

Prefabs of UI elements are instantiated as normal using the Instantiate method. When setting the parent of the instantiated UI element, it’s recommended to do it using the Transform.SetParent method with the worldPositionStays parameter set to false.

There are 2 problems that I don’t know how to tackle:

  1. Drawing the prefab image on the UI.
  2. Drawing it at the correct position (i.e. directly under the touch position in screen space).

Can anyone provide some C# example code to help achieve this? I have tried using the “Transform.SetParent method” (as advised here) but I’m not having much luck figuring out how to implement it.


Finally got that to work. Followed advice from @Xabrough and made the icon an image on my canvas, disabling it in the editor and then enabling it from script.

If anyone else gets stuck:

public class icon : MonoBehaviour
	public GameObject icon;

	public void createIcon (Vector2 touchPos) {
		icon.transform.position = new Vector3(touchPos.x, touchPos.y, 0);
	public void destroyIcon () {

Then call these functions from the correct places in your input handling script, passing the position of the touch to createIcon.

If you’re using a UI image on a canvas, you could simply but it on there in the editor and then enable it when you press the mouse, then set its transform.position = Input.mousePosition and disable it after a few seconds or on MouseUp. Instantiating would only eat up cpu resources.

I just don’t understand, when exactly .enable replaced instantiate ?