Solved
Game Object doesn't instantiate at Mouse Position
I'm working on an incremental game and to start gaining coins you need to click a button. What I wanted to do was every time I hit the button, it instantiates a little hit sprite to give the user visual feedback. The problem is it just instantiates at the middle of the canvas instead of at the mouse position. Here's what I currently have: (If you need more information tell me)
public void OnClick()
{
InstantiateHit();
}
public void InstantiateHit()
{
var mousePos = Input.mousePosition;
var PositionHit = new Vector3(Camera.main.ScreenToWorldPoint(mousePos).x, Camera.main.ScreenToWorldPoint(mousePos).y, transform.position.z);
GameObject hit = Instantiate(Hit, PositionHit, Quaternion.identity) as GameObject;
hit.transform.SetParent (GameObject.FindGameObjectWithTag("Canvas").transform, true);
}
Answer by Cuttlas-U · Mar 09, 2018 at 12:40 PM
hey; why do u make it as a canvas parent ?
this may cause problems;
You're right, after reading his code, when he sets the canvas as the parent and adds the secondary true argument. It gives up its current position. It should be false as the second argument in SetParent
Answer by Aether808 · Mar 10, 2018 at 10:07 AM
I removed the part of the code that makes it a Parent of the Canvas because apparently that was the issue but it still doesn't get instantiated at the mouse position. And when I put the position of the prefab to 0, 0 I can't even see the object :/ really don't know what's going on.
var mousePos = Input.mousePosition;
var PositionHit = new Vector3(Camera.main.ScreenToWorldPoint(mousePos).x, Camera.main.ScreenToWorldPoint(mousePos).y, transform.position.z);
Instantiate(Hit, PositionHit, Quaternion.identity);
Change new Vector3(Camera.main.ScreenToWorldPoint(mousePos).x, Camera.main.ScreenToWorldPoint(mousePos).y, transform.position.z);
To
new Vector3(Camera.main.ScreenToWorldPoint(mousePos).x, Camera.main.ScreenToWorldPoint(mousePos).y, 0);
I replaced my code with yours and I can now see the object being instantiated but it's not a the mouse position it's in the corner of the screen :/
Answer by Aether808 · Mar 12, 2018 at 08:01 AM
I think the problem isn't with the code but maybe with the way I setup my prefab or maybe in my game somehow. Is there some way I can make sure?