Cannot instantiate 2D prefab on mouse click
Hello!
I'm working in 2D mode and I've got a prefab called "square" which is just a sprite of a square that I want to instantiate upon mouse click. I attached a script to my main camera with the following code:
public Canvas canvas;
public GameObject square;
void Update () {
if (Input.GetMouseButtonDown(0)) //Left mouse click
{
GameObject obj = (GameObject)Instantiate(square,
new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0), Quaternion.identity);
}
}
I attached my sprite prefab to the camera so that the GameObject square is referencing it. I've also tried hard coding the x and y values to values which I know should appear within the canvas. I should mention that the camera's z-coordinate is -10, less than the value of the instantiated object's z-coordinate.
So how can I get my sprite to appear?
Thanks!
EDIT:
Adding some screenshots. My Sprite:
My Camera:
EDIT:
So maca's answer below ended up being quite helpful. After some hours of testing and reading posts I found that what I was missing was the fact that ScreenToWorld
doesn't work with a z-coordinate equal to that of the camera's (see this post). Setting the parent of my instantiated object to the canvas transform was also necessary (although I used the new SetParent()
function), and I had to rescale my sprite a bit.
Thanks to the community and especially @maca for the help!
Answer by LucianoMacaDonati · Dec 30, 2016 at 09:14 PM
If your object is a UI element then it must be under a Canvas parent. You could achieve this by following your code with obj.transform.parent = canvas.transform;
Hey @maca, thanks so much for the reply! I did try this and it didn't seem to have any effect. Is there anything else I'm missing?
Is your prefab a SpriteRenderer or an Image ? Also, remember that Input.mousePosition is in ScreenSpace, not WorldSpace. Camera.main.ScreenToWorldPoint(Input.mousePosition) could give you the correct position. If none of that helps, then I will need more information in order to help you =D
Hello. $$anonymous$$y prefab is a SpriteRenderer. I just tried the suggestion you gave, but I got the same results. I think the coordinates are not the problem (or not the only problem) since using hard coded values also doesn't work.
For sure, what additional information can I provide that would help? Thanks so much for your assistance here!
Your answer
![](https://koobas.hobune.stream/wayback/20220612103735im_/https://answers.unity.com/themes/thub/images/avi.jpg)