- Home /
How to Instantiate object on mouse click at mouse cursor position?
I want to instantiate a arrow as a gameobject where i click and destroy arrow when another mouse click and instantiate on another mouse position just like strategy game.
If your game is a first person game, you can add a GameObject to your camera hierarchy and use it's transform as source position for the arrow instance.
If you're creating a strategy game and you want to instantiate a object on the mouse position, you can do a Physics.Raycast from the camera position to your mouse position and find out where the ray collided, get the collision point and instantiate the object there. On the Raycast page you'll find an example script showing how to raycast from the camera to the mouse position.
Answer by robertbu · Jan 16, 2013 at 03:30 PM
"Instantiate...where I click" is a bit complex in Unity because you are mapping your screen into a 3D space. Here is a starter script. Attach it to an object. The object will move to where you clicked. Note the oject is placed at 0.0 on the Z axis. Place this on an empty game object and you can modify it to Instantite game objects at a position.
using UnityEngine;
using System.Collections;
public class MoveObject : MonoBehaviour {
Plane plane;
void Start ()
{
plane = new Plane(Vector3.forward, Vector3.zero);
}
void Update ()
{
if (Input.GetMouseButtonDown (0))
{
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
float fDist = 0.0f;
plane.Raycast (ray, out fDist);
transform.position = ray.GetPoint (fDist);
}
}
}
Thanks for reply but I am working on 2D game where orthographic camera is used. In game my player move where i click but I want to instantiate a arrow as gameobject that shows where player is going to move. Your script is very good but i want according to above. Thanks Again.
The above script will do the job with just a couple of $$anonymous$$or changes. Note there if is only a single arrow that disappears when the character reaches the destination, you might be better off just moving/hiding/showing the arrow rather than creating and destorying the arrow.
Your answer
![](https://koobas.hobune.stream/wayback/20220613091031im_/https://answers.unity.com/themes/thub/images/avi.jpg)