- Home /
Create objects on a mouse click in 2D
Ive looked up many ways to try this but it never works. Im trying to make a platform prefab spawn at the mouse when its clicked. Again though, this is in 2D! If you know how to, please tell me but nothing will work for me. Heres my code:
using UnityEngine;
public class ObjectCreation : MonoBehaviour {
public Transform Prefab;
void Start()
{
}
void Update () {
if(Input.GetMouseButton(0))
{
Instantiate(Prefab, new Vector3(Input.mousePosition.x, Input,mousePosition.y, 0), Quaternion.identity);
}
}
}
EDIT:
Thanks a lot @Luo_Yang for the help. I had a different result but this question is now answered.
Answer by kalen_08 · Jul 26, 2018 at 09:58 PM
You need to pass in 0 or 1 into getMouseDown for either the left or right buttons.
You have calculated the mouse position but never use it. Instead of using Plat use mousePosition.
That isnt the problem, the transform.position is for a crosshair, so it is used and the getmousedown was a guess on what i did before. i didnt copy and paste this so i got some wrong. Secondly: why would i use mouseposition in instantiate? Plat is the prefab being copied. I just updated the code to what it actually was and removed the crosshair code so its less confusing. Take a look if you dont $$anonymous$$d, thanks.
Didn't you say you wanted the prefab spawned at the mouse position? What I was saying is use that same position you calculated to place the cross hairs and use that as the spawn position if that's what your trying to do.
@kalen_08 UPDATE! i just fiddled with the code and now it duplicates the prefab once but it doesnt show up...(it is a sprite) what should i do?
The mouseposition is screen positon. You need to convert the position into world position or UGUI position to use them. Camera.ScreenToWorldPoint
@Luo_Yang Thanks for your time and great advice, but what i did ins$$anonymous$$d is base the platform spawn off of my crosshair's position. Thanks a lot though!