- Home /
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:
Drawing the prefab image on the UI.
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.
Thanks
Answer by Makkasu · Jun 16, 2015 at 05:44 AM
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.SetActive(true);
icon.transform.position = new Vector3(touchPos.x, touchPos.y, 0);
}
public void destroyIcon () {
newJoystick.SetActive(false);
}
}
Then call these functions from the correct places in your input handling script, passing the position of the touch to createIcon.
Answer by Xarbrough · Jun 14, 2015 at 11:55 PM
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.
Followed this advice and will post my solution separately, thanks!
Answer by IsouEU · Dec 28, 2021 at 12:29 PM
I just don't understand, when exactly .enable replaced instantiate ?
Your answer
Follow this Question
Related Questions
Ui sidescroller 2d touch ? 0 Answers
Changing multiple toggle states. 0 Answers
Touch Buttons 0 Answers
Unity UI button does not detect click 2 Answers
UI Image has no sprite definition 0 Answers